Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Animator in abstract class returns null

Discussion in 'Scripting' started by Deleted User, Sep 10, 2023.

  1. Deleted User

    Deleted User


    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
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    5. public class Zombie1 : MonoBehaviour
    6. {
    7.   private GameObject player;
    8.   private Animator zombieAnim;
    10.    private void Awake()
    11.   {
    12.    player = GameObject.FindWithTag("Player");
    13.    zombieAnim = GetComponent<Animator>();
    14.    }
    16.    private void OnCollisionEnter(Collision collision)
    17.    {
    18.     if (collision.gameObject.CompareTag("Player"))
    19.     {
    20.     zombieAnim.SetBool("IsCloseEnough", true); // Start animations if zombie is close enough to the player
    21.     }
    22.   }
    23. }
    and the attempt at the abstract class is
    Code (CSharp):
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    6. public abstract class Enemy : MonoBehaviour
    7. {
    8.   protected Animator anim;
    9.   protected GameObject player;
    10.   private void Start()
    11.   {
    12.     player = GameObject.FindWithTag("Player");
    13.     anim = GetComponentInChildren<Animator>();
    14.     if (anim == null)
    15.     {
    16.      Debug.LogError( + "Animator is NULL");
    17.     }
    18.   }
    20.    protected void OnCollisionEnter(Collision collision)
    21.    {
    22.     if (collision.gameObject.CompareTag("Player"))
    23.     {
    24.       anim.SetBool("IsCloseEnough", true);
    25.     }
    26.    }
    27. }
    with the change
    public class Zombie1 : Enemy
    in the initial script. The error I get is a nullreferenceexception. Any thoughts?
  2. Kurt-Dekker


    Mar 16, 2013
    The answer is always the same... ALWAYS!

    How to fix a NullReferenceException error

    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
    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

    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: or this answer for 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!(tm)" - Kurt Dekker (and many others)

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

    Deleted User


    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.
  4. Kurt-Dekker


    Mar 16, 2013
    Do this for the Animator.

    Keep in mind that using GetComponent<T>() 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(tm) and make dedicated public fields and drag in the references you want.

    Then you're not looking on the correct GameObject. Print out the
    field and find out.
  5. Deleted User

    Deleted User


    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!
  6. Kurt-Dekker


    Mar 16, 2013
    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
    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.
    Bunny83 likes this.
  7. Bunny83


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