Accessing a variable from a script that is StateMachineBehavior

I have this script attached to my run animation

public class Boss_Run : StateMachineBehaviour
{
    public float speed = 5f;
    public float attackRange = 3.5f;
...

I won’t post the whole the thing… you get the idea.

I want to access the speed variable in the script above in another script that is attached to the gameobject that is running

public class Enemy : MonoBehaviour
{
   Boss_Run bossRun;

....

In my Start method of the Enemy script I have this:

bossRun = FindObjectOfType<Boss_Run>();

Later in the script in another method I attempt to change the speed using this line of code:

bossRun.speed += (hpPCT * bossRun.speed) / 100;

This throws the error NullReferenceException: Object reference not set to an instance of an object

I am sure it has something to do with FindObjectOfType<Boss_Run>();

What are your thoughts?

You probably haven’t instantiated an instance of Boss_Run anywhere.

It appears that a StateMachineBehaviour will be instantiated by the Animator. I don’t remember when the Animator does its business relative to Start, so that could be the problem.

More generally, you probably don’t want to use FindObjectOfType<>() because it’s very slow.

[quote]
I want to access the speed variable in the script above in another script that is attached to the gameobject that is running
[/quote]I think you’re overcomplicating the problem. This should be pretty easy. It would be a good idea to go through Animator-related tutorials to see the best practices for changing a float like that.

1 Like

This right here. You are absolutely correct. I was way over thinking this issue.