Object reference not set to an instance of an object

  • Of course, the title explains the situation.



    here is the error

    Code
    1. NullReferenceException: Object reference not set to an instance of an object
    2. Enemy.Update () (at Assets/Scripts/Enemy/Enemy.cs:37)


    To me I don't understand what its trying to tell me or why i'm getting this error.

    I looked through the code and everything seems to make sense., the program runs perfectly but I just don't know why I am still getting this error.


    Here is the script that it is referring to:

  • So, an object reference not set to an instance error means that you've got a component/gameobject/etc.. that you're calling, but Unity can't find it where you said it'd be. Line 37:

    1. if (anim.GetCurrentAnimatorStateInfo(0).IsName("Idle"))

    what is being referenced here? The anim variable is being called on, which is the variable you created to reference an Animator class. So you backtrack.

    Code
    1. anim = GetComponentInChildren<Animator>()

    Here you get where you're telling the variable where to find a reference. You're telling it the Animator class you're accessing can be found as a component of the child of this object. What's likely wrong here, is you've got some enemy without an Animator component somewhere, so though your code appears to run fine, i'm guessing somewhere there's an enemy whose animations aren't working because the script can't find it's animator.

  • Post by atoi ().

    This post was deleted by the author themselves: incorrect info ().
  • I doubt your problem is in code, but there is mine from the same lesson presumably. Maybe a little farther along. I would bet you already have it figured out by now. :)

  • This line of code in Update seems to be causing the problem:


    Code
    1. if (anim.GetCurrentAnimatorStateInfo(0).IsName("Idle"))
    2. { return; }


    Code
    1. nullcheck that anim component. if (anim == null)
    2. Debug.Log("Anim is null on: " + this.name); 


    I think you may have accidentally added the script onto another gameObject. this will print out the name of the object it's null on. Add this above the current if check you have in update