Home > OS >  Unity 3D - why i dont see error for this simple line of code with Collider2D method
Unity 3D - why i dont see error for this simple line of code with Collider2D method

Time:01-11

public class move : MonoBehaviour
{
    Animator animator;
    bool dirToRight = true;
    Rigidbody2D rigidbody;
    public float heroSpeed;
    bool onGround;
    public Transform groundTester;
    public float radius;
    public LayerMask layerMask;

    // Start is called before the first frame update
    void Start()
    {
        
        animator = GetComponent<Animator>();  
        rigidbody = GetComponent<Rigidbody2D>();    
    }

    // Update is called once per frame
    void Update()
    {
 
       onGround = Physics2D.OverlapCircle(groundTester.position, radius, layerMask);
}
}

I dont understand why bool "onGround" field not show error message, its bool type not Collider2d, the Physics2D.OverlapCircle() return Collider2D object not bool...... why please explain this magic for me....

CodePudding user response:

I believe, it's synthetic sugar or shorthand for if(onGround) or if(onGround != null).

CodePudding user response:

Physics2D.OverlapCircle returns a Collider2D which is a Behaviour which is a Component which is a UnityEngine.Object which has an implicit bool operator

Does the object exist?

it basically return the same as

onGround = Physics2D.OverlapCircle(groundTester.position, radius, layerMask) != null;
  •  Tags:  
  • Related