Animator in abstract class returns null

Hi! I have a script in which an enemy attacks the player when their boxes collide, which works great. I tried to implement an abstract class to initialise all the different enemies, but when I get the animator from this abstract class, null is returned. Why is that?

The working script is

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Zombie1 : MonoBehaviour
{
  private GameObject player;
  private Animator zombieAnim;

   private void Awake()
  {
   player = GameObject.FindWithTag("Player");
   zombieAnim = GetComponent<Animator>();
   }

   private void OnCollisionEnter(Collision collision)
   {
    if (collision.gameObject.CompareTag("Player"))
    {
    zombieAnim.SetBool("IsCloseEnough", true); // Start animations if zombie is close enough to the player
    }
  }
}

and the attempt at the abstract class is

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Enemy : MonoBehaviour
{
  protected Animator anim;
  protected GameObject player;
  private void Start()
  {
    player = GameObject.FindWithTag("Player");
    anim = GetComponentInChildren<Animator>();
    if (anim == null)
    {
     Debug.LogError(transform.name + "Animator is NULL");
    }
  }

   protected void OnCollisionEnter(Collision collision)
   {
    if (collision.gameObject.CompareTag("Player"))
    {
      anim.SetBool("IsCloseEnough", true);
    }
   }
}

with the change public class Zombie1 : Enemy in the initial script. The error I get is a nullreferenceexception. Any thoughts?

The answer is always the sameā€¦ ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ā† any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

If you have no idea what order things are initializing in (common with inheritance patterns), then FIX THAT FIRST. Hereā€™s how:

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • youā€™re getting an error or warning and you havenā€™t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Hereā€™s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

ā€œWhen in doubt, print it out!ā„¢ā€ - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

The null exception occurs because anim is null. For some reason, the line anim = GetComponentInChildren<Animator>(); does not pick the Animator component of my subclass Zombie1, so I know the problem comes from this point (Iā€™ve put Debug.Logs everywhere to know that). The rest of my parent class (Enemy) works fine, since Iā€™ve declared variables in it that I can access in the inspector.

Do this for the Animator.

Keep in mind that using GetComponent() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.

This sort of coding is to be avoided at all costs unless you know exactly what you are doing.

If you run into an issue with any of these calls, start with the documentation to understand why.

There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.

In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.

It is ALWAYS better to go The Unity Wayā„¢ and make dedicated public fields and drag in the references you want.

Then youā€™re not looking on the correct GameObject. Print out the name field and find out.

Found the error! I provided the Start method with a private keyword, so I guess Zombie1 couldnā€™t access the Animator that was initialised in Enemy. Replacing it by protected solved the error. Thanks for the help!

This is the problem with using inheritance in Unity: the average Unity engineer does not expect it.

Yes you can use it.

Yes some engineers expect it.

Yes it works fine when you do expect and respect it.

But you will constantly run into people who forget to call base.Start() et al in the general Unity community.

Unity is a Component architecture (largely) at the scripting level. I find it better to think in those terms so that I am in harmony with the underlying structure of the engine. YMMV.

1 Like

Right, also if the base class defines a Unity callback, it should be declared protected.