Search code examples
c#unity-game-enginecollisionunity-components

Unity modify component property after collision


I'm trying to modify a property of a class component after collision, but the property doesn't seem to be set.

void OnCollisionExit2D (Collision2D myCollision) {
    Debug.Log ("OnCollisionExit2D in Player:" + myCollision);
    CompoMyClass compo = myCollision.gameObject.GetComponent<CompoMyClass>();
    if (compo.collideOnce == true)
        return;
    compo.collideOnce = true;
    // it always goes here :(
}

Do you know why?

public class CompoMyClass : MonoBehaviour {
    public bool collideOnce  = false;

    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {
    }
}

Solution

  • Make sure that you're looking at the same instance of the Component per collision. If this component were attached to multiple objects, each would have their own collideOnce variable to worry about.

    A good way to do this, which will unambiguously tag each object, is to assign an ID such as

    Guid ID = Guid.NewGuid();
    

    Also make sure that the object you're colliding with has the right component, to prevent a NullReferenceException, and that you're exiting the collision properly. You may want to switch to OnCollisionEnter.

    finally, make sure you're not setting that value false anywhere else.