- Home /
Object Reference and Instancing Problem
Hello! Got a script I wanna fire upon collision right heree...
void OnTriggerEnter(Collider col)
{
var target = col.gameObject;
var com = target.GetComponent<PlayerStateSync>();
bool isSneaking = com.crouching;
Debug.Log(isSneaking);
}
Got no errors when I compile, no errors at runtime UNTIL the collision happens and throws
NullReferenceException: Object reference not set to an instance of an object
MyScript.OnTriggerEnter (UnityEngine.Collider col) (at Assets/Game Scripts/MyScript.cs:22)
So the error is happening where I'm declaring the bool. Not really sure what's going on... I'm guessing the error message should be self explanatory... :/
Hum.
Hello again! That was indeed the problem! The object I was colliding with is the child of the object that actually has PlayerStateSync attached.
I've solved it by changing this line:
var target = col.gameObject.transform.parent;
Pretty basic stuff, sorry for troubling you!
Don't forget to mark the answer as accepted so all the happy feelings can go all over the place :>
Answer by hiddenspring81 · May 30, 2013 at 07:28 PM
Are you sure that the objected you collided with has an instance of PlayerStateSync
attached? You should add a simple guard statement to the top of your OnTriggerEnter
method,
void OnTriggerEnter (Collider col)
{
var target = col.gameObject;
var com = target.GetComponent<PlayerStateSync>();
if (com == null)
{
Debug.Log("Doesn't have PlayerStateSync attached");
return;
}
// Everything else here
}