I am new to Unity and have run into a snag. I am attempting to trigger the animations for two doors whenever the player collides with the trigger. When the objects collide, i get the error “NullReferenceException: Object reference not set to an instance of an object”. Here is the problem code:
if (col.gameObject.name == "DoorTrigger")
{
anim2.GetComponent<Animator>().Play("LeftDoorAnimation");
anim.GetComponent<Animator>().Play("RightDoorAnimation");
}
The line the error references is anim2.
I have verified that i have connected the door GameObjects to the public variable in the inspector and have no errors in my code.
Thanks.
Well, the first thing is to know what’s producing the null. It could be many things:
if (col.gameObject.name == "DoorTrigger")
{
//First, you need to space the terms to see wich one is it that it's producing the error :
anim2.//If it's this line, you don't have "anim2"'s reference.
GetComponent<Animator>().//If it's this one, anim2 doesn't have a valid animator component, or you could forgot to add the animator file to the actual animator component.
Play("LeftDoorAnimation"); //Or it may not be finding this animation (it could be misspelled for example, or the state could be missplled in the animator, or it could be in some layer that you haven't specified)
anim.GetComponent<Animator>().Play("RightDoorAnimation");
}
So, check that and narrow it down.