Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Null Exception on working script using AI and Animator

Discussion in 'Scripting' started by FunnyGuy, Sep 18, 2020.

  1. FunnyGuy

    FunnyGuy

    Joined:
    Apr 14, 2014
    Posts:
    13
    Ran into an issue last night with my AI script (which was working). The issue has caused the script to stop working and there are no changes to the script, which is why this issue is odd for me. Note: I have removed most variables and unnecessary code.

    NullReferenceException: Object reference not set to an instance of an object
    AI.UpdateAnimator () (at Assets/My Stuff/My scripts/AI.cs:122)
    AI.Update () (at Assets/My Stuff/My scripts/AI.cs:54)



    I will show the 3 parts of concern:
    Code (CSharp):
    1.  
    2.  
    3.  
    4. using UnityEngine;
    5. using UnityEngine.AI;
    6.  
    7.  
    8. public class AI : MonoBehaviour
    9. {
    10.     #region Variables
    11.  
    12.  
    13.     public float lookRadius = 10f;
    14.  
    15.     Transform target;
    16.     NavMeshAgent agent;
    17.     Animator animator;
    18.     GameObject PlayerObj;
    19.    
    20.  
    21.     public int maxHealth = 200;
    22.     public int health = 200;
    23.     public int minHealth = 0;
    24.  
    25.     public float deathWait = 0.03f;
    26.  
    27.     public bool isDead = false;
    28.  
    29.  
    30.  
    31.    public bool isHitting;
    32.  
    33.     #endregion
    34.  
    35.  
    36.     void Start()
    37.     {
    38.        
    39.         PlayerObj = GameObject.FindGameObjectWithTag("Player");
    40.        agent = GetComponent<NavMeshAgent>();
    41.         target = PlayerManager.instance.player.transform;
    42.         animator = GetComponent<Animator>();
    43.         health = maxHealth;
    44.      
    45.     }
    46.  
    47.    
    48.     void Update()
    49.     {
    50.         isHitting = PlayerObj.GetComponentInChildren<Controls>().swinging;
    51.         if (isDead == false)
    52.         {
    53.             Debug.Log("Is Start");
    54.             UpdateAnimator();
    55.             float distance = Vector3.Distance(target.position, transform.position);
    56.  
    57.             if (distance <= lookRadius)
    58.             {
    59.                 agent.SetDestination(target.position);
    60.  
    61.                 if (distance <= agent.stoppingDistance)
    62.                 {
    63.                     FaceTarget();
    64.                    
    65.                     Attack();
    66.  
    67.                 }
    68.  
    69.             }
    70.         }
    71.         if (health <= minHealth)
    72.         {
    73.            
    74.             isDead = true;
    75.             Invoke("Die", deathWait);
    76.         }
    77.  
    78.  
    79.  
    80.     }
    81.  
    82.     private void Attack()
    83.     {
    84.        int DMG = GetComponentInChildren<WeaponItem>().weaponItem.weaponDMG;
    85.         animator.SetTrigger("Attack");
    86.     }
    87.  
    88.     void Die()
    89.     {
    90.         if (isDead)
    91.         {
    92.            
    93.             animator.SetBool("Die", true);
    94.             animator.ResetTrigger("Attack");
    95.          
    96.         }
    97.     }
    98.  
    99.     void FaceTarget()
    100.     {
    101.         Vector3 direction = (target.position - transform.position).normalized;
    102.         Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
    103.         transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
    104.         Debug.Log("Looking at player");
    105.     }
    106.  
    107.     #region Gizmos
    108.     private void OnDrawGizmosSelected()
    109.     {
    110.         Gizmos.color = Color.red;
    111.         Gizmos.DrawWireSphere(transform.position, lookRadius);
    112.     }
    113.  
    114.     #endregion
    115.  
    116.    private void UpdateAnimator()
    117.     {
    118.         Debug.Log("Moving by animation");
    119.         Vector3 velocity = agent.velocity;
    120.         Vector3 localVelocity = transform.InverseTransformDirection(velocity);
    121.         float speed = localVelocity.z;
    122.         animator.SetFloat("MoveSpeed", speed);
    123.     }
    124.  
    125.     private void OnTriggerEnter(Collider other)
    126.     {
    127.         if (other.CompareTag("Axe") && isHitting)
    128.         {
    129.             health -= PlayerObj.GetComponentInChildren<WeaponItem>().weaponItem.weaponDMG;
    130.             health = Mathf.Clamp(health, 0, maxHealth);
    131.          
    132.             Debug.Log(health);
    133.         }
    134.  
    135.         if (other.CompareTag("PickAxe"))
    136.         {
    137.             Debug.Log(health);
    138.         }
    139.  
    140.         if (other.CompareTag("Sword"))
    141.         {
    142.             Debug.Log(health);
    143.         }
    144.  
    145.  
    146.     }
    147.  
    148.    
    149. }
    150.  
    The variables are already defined and in their correct location at the top of the script or within a local scope. The script was working for about a week, with the only change being a SendMessage() to another script in an unaffected if statement.

    The editor also gave a null exception for this line when I removed UpdateAnimator():
    float distance = Vector3.Distance(target.position, transform.position);


    Can anyone tell what's the issue? My Animator has the proper parameters "MoveSpeed" using a blend tree and was working fine. The Debug.Log in UpdateAnimator() does run, and line number for the error rests at:
    animator.SetFloat("MoveSpeed", speed);
     
    Last edited: Sep 18, 2020
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    Could you show the whole script?

    there is an error at 122 and 54, your script doesnt provide those lines
     
  3. FunnyGuy

    FunnyGuy

    Joined:
    Apr 14, 2014
    Posts:
    13
    Line 122 here is line 43.

    Line 54 here is line 18.

    Give me a moment and I'll edit the post to include the full script
     
  4. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    the animator is null , looks to me,

    do you have an animator script on your component?
     
  5. FunnyGuy

    FunnyGuy

    Joined:
    Apr 14, 2014
    Posts:
    13
    The GameObject has an Animator component and the AI.cs script, along with the animator controller. Script has been updated.
     
  6. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    try something like that:

    Code (CSharp):
    1. if(animator) {
    2.         animator.SetFloat("MoveSpeed", speed);
    3. } else {
    4.         print("Animator Component not attached");
    5. }
     
    FunnyGuy likes this.
  7. FunnyGuy

    FunnyGuy

    Joined:
    Apr 14, 2014
    Posts:
    13
    That's a good one. Yep, it's saying it's not attached.
     
  8. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    try to get your components in "Awake",

    and add something like that to your class, after saving the class, remove the component from your gameobject and reattach it to it

    Code (CSharp):
    1. [RequireComponent(typeOf(Animator))
    2. public class AI : MonoBehaviour
    3.  
    you need to check if its right written since im writing in here in the browser
     
  9. FunnyGuy

    FunnyGuy

    Joined:
    Apr 14, 2014
    Posts:
    13
    Awesome, thanks! Only when I moved the Start() code to Awake did it finally work. Weird. Thanks again!
     
    Kurt-Dekker and Terraya like this.
  10. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,517
    There is likely a reason and you can ultimately figure out, if you care... check this out:

    Here is some timing diagram help:

    https://docs.unity3d.com/Manual/ExecutionOrder.html

    ALSO... for any nullref you might encounter in the future (AND YOU WILL! :) ), the key is to get over it fast. Here's some more reading:

    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.
     
    FunnyGuy and Terraya like this.