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

trying to trigger animation event and getting NullReferenceException

Discussion in 'Scripting' started by threed-m, Dec 30, 2019.

  1. threed-m

    threed-m

    Joined:
    Jul 4, 2019
    Posts:
    3
    as you can tell im new and really trying here for hours but im at a loss-

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayMyAnimation : MonoBehaviour
    6. {
    7.     [SerializeField] private Animator myAnimationController;
    8.  
    9.     private void OnTriggerEnter(Collider other)
    10.     {
    11.         if (other.comparetag("Player"))
    12.         {
    13.             myAnimationController.SetBool("playbikemove", true);
    14.         }
    15.     }
    16.  
    17.  
    18.     private void OnTriggerExit(Collider other)
    19.     {
    20.         if (other.comparetag("Player"))
    21.         {
    22.             myAnimationController.SetBool("playbikemove", false);
    23.         }
    24.     }
    25. }
    26.  
    i want to walk into a box collider and have it trigger the animation, when i walk out it should stop the animation. but its not working at all, i followed a tutorial and it works for others so i dont know.
     
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    First thing to check is if "myAnimationController" has been assigned in the inspector.

    Next thing to check is if the functions are even being called. You could use a Debug.Log to print something in the console.

    The OnTriggerEnter/Exit/Stay functions require a rigidbody to work. Ensure that your player has a rigidbody component attached to it.

    On a side note, does this code compile? Isn't it supposed to be "CompareTag".
     
    threed-m likes this.
  3. VSM2018

    VSM2018

    Joined:
    Jun 14, 2018
    Posts:
    16
    Add myAnimationController = GetComponent<Animator>.() if the Animator is attached to the gameobject.
     
    Last edited: Dec 30, 2019
  4. threed-m

    threed-m

    Joined:
    Jul 4, 2019
    Posts:
    3
    after adding rigidbody and changing comparetag it seems to be getting closer but i now get this error-
    "cannot add component because script class cannot be found. make sure the file name and class match and check for compile errors."

    they do match and everything looks good in visual studio.
     
  5. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Locate the .cs file containing this class and rename it to "PlayMyAnimation".