Home > Net >  Collider2D.bounds is required for non static field on check ground script
Collider2D.bounds is required for non static field on check ground script

Time:04-06

i'm creating a check ground script and on Collider2D.bounds it shows an error An object reference is required for the non-static field, method, or property 'Collider2D.bounds'

There script:

public class PlayerScript : MonoBehaviour
{
[SerializeField] float speed = 10f;

private Animation rotate_anim;
// Start is called before the first frame update
void Start()
{
    rotate_anim = GetComponent<Animation>();
}

// Update is called once per frame
void Update()
{
    Jump();
}
void Jump(){
    //not there
}
private bool isGrounded(){
    RaycastHit2D raycasthit2d = Physics2D.BoxCast(CircleCollider2D.bounds.center, CircleCollider2D.bounds.size, 0f, Vector2.down * 1f);
    return raycasthit2d.collider !=null;
}

}

CodePudding user response:

You need to access an instance of the CircleCollider2D class, while you're trying to access the class itself. When you try to access the class, you can only use static methods because there is no way for the runtime to know which instance of the class you are trying to access. First you need to get the collider component attached to your player in your Start method just like you did with the Animation

private Animation rotate_anim;
private CircleCollider2D collider;
// Start is called before the first frame update
void Start()
{
    rotate_anim = GetComponent<Animation>();
    collider = GetComponent<CircleCollider2D>();
}

Next you need to provide the collider to the BoxCast function

RaycastHit2D raycasthit2d = Physics2D.BoxCast(collider.bounds.center, collider.bounds.size, 0f, Vector2.down * 1f);
  • Related