Calling public animator method from another object.

Hi All,

I’m a bit stumped on this one. I hope one of you can assist.
I want to trigger an animation event from a different object / script, but I seem to be getting Null ref exceptions.

See below. the Animator resides on Script A (with a public method that sets the animator bool), I want to call the method from Script B and set it from there:

ScriptA:

public class ScriptA: MonoBehaviour
{

    Animator animator;

void Start()
    {
        animator = GetComponent<Animator>();
    }

  public void SetAnimatorBool(bool v)
    {
        animator.SetBool("isMouseButtonDown", v);
    }
}

ScriptB (Calling Method from here):

public class ScriptB: MonoBehaviour
{

    scriptA ScriptA;


void Start()
    {
        scriptA = FindObjectOfType<ScriptA>();
        
    }

void Update()
   {
      
  if (Input.GetMouseButtonDown(0))
        {
            scriptA.SetAnimatorBool(true);
        }
   }

    }

Any Reason why this is not working? I have used public methods in exactly the same way in the past without any issues.

Thanks in advance!

FindObjectOfType<ScriptA>(); is returning null. That means there is no ScriptA object in your game world at the time that Start() on your ScriptB is called. Is there a ScriptA in your scene anywhere at edit time? Are you creating it at runtime via Instantiate() perhaps?

Hi. Yup it’s in the scene from the start and it’s not being instantiated

Well wait where are you getting the NullReferenceException. Is it inside SCriptA or inside ScriptB?

If it’s inside ScriptA, Animator is null, which means you don’t have an Animator attached to the same object as your ScriptA object.

If it’s inside ScriptB, ScriptA is null.

I’m getting it from ScriptB (so ScriptA is null). I’m clueless as to why as everything seems to be correct and in place. I’ll have to investigate some more. Thanks for your assistance so far!

Your “scriptA” vs “ScriptA” naming is messed up.

Line 4 should be “ScriptA scriptA;”