- Home /
If statement null check not working as expected
In my scene I have a ball and I want to store a reference to the first Collision it encounters. I have two GameObjects in the scene, each with a unique tag. With the following code I expect the variable to only be updated on the first collision, however it is being updated on every collision to the most recent collision.
public class GolfBallCollision : MonoBehaviour {
public Collision contactFirst = null;
public void OnCollisionEnter(Collision collision)
{
CheckFirst(collision);
Debug.LogWarning(contactFirst.gameObject.tag);
}
public void CheckFirst(Collision hit)
{
if (contactFirst == null)
{
contactFirst = hit;
}
}
}
What happens when I try this is the the log prints the tag of whichever GameObject it collided with LAST instead of just the first one every time. Please let me know if any additional information is needed, thanks.
Hmm $$anonymous$$aybe that collision passed into the event handlers is always pointing to a single collision object which is updated. Let me recreate the problem.
Where is this script attached? If this script is attached to the golf ball only, it should be fine. However, if you have attached multiple times this component (on multiple obstacles for example), this script must be changed.
Answer by sacredgeometry · Aug 11, 2019 at 03:32 PM
Yes its as I thought, the collision object passed into the event handlers is a reference to a single object in memory not a new object each time it is called.
to expound on that
// once contactFirst is set is equivalent to
contactFirst == hit
You could copy it and then store a reference to the copy in the variable instead.
Is there anything in particular you are looking to store about the collision object?
Do you know if this is a change from previous version? I'm only running into this while attempting to update my project from 2018 to 2019. Can you tell me how you tested this or where you found the information? Please forgive my ignorance.
Basically I have a tag for 'targets' and a tag for 'environment' and want to check if it's a direct hit on the target or a bounce hit.
I just did a referential equality test on the two objects
i.e.
Debug.Log(collision == contactFirst);
it was always true.
You can add additional logging to see that it does infact only jump into that if statement once (I assume) or add a break point and debug it.
Also: I don't know if thats changed but one way to find out is if they changed the Collision from a struct to a class.