Question about how getcomponent should work. throwing an error when i try to run.

    void GetIdleVariables()
        GetComponent<IdleManager>().count += idleCount;


trying to get this script to call in the variable count from IdleManager script, and then make it = to the private variable on this script i set up called idleCount. I am going to then save the variable idleCount. Everything appears to look fine in the scrip, and no errors get thrown, but when i go in and run it it comes back saying that nullrefrenceexception. object refrence not set to an instance of an object. could someone explain to me what i am not having connected? im not quiet sure what i would need to connect. thanks

Null reference exception generally means that something before a dot is null. In this case GetComponent() is returning null.

A quick check of the documentation reveals that GetComponent returns null when the component is not attached to the GameObject.

So in short there is no script called IdleManger on the same GameObject as this script.

If you have the IdleManager script on another object, you'll have to use a different method to access it. There are a couple basic ways to do this.

The first way to access it is to search for the GameObject it is attached to by name and retrieve the script from it.

GameObject go = GameObject.Find("name of object it is attached to");
go.GetComponent<IdleManager>().count += idleCount;

The second way is to search for the script component itself. You can either go with the first instance of it found.

IdleManager manager = FindObjectOfType(typeof(IdleManager)) as IdleManager;
manager.count += idleCount;

Or you can search for every single instance and update all of them.

IdleManager[] managers = FindObjectsOfType(typeof(IdleManager)) as IdleManager[];
foreach (IdleManager m in managers) {
   m.count += idleCount;
1 Like

Its also worth mentioning assigning references in the inspector. This is by far the most common way I use.

[quote=“Kiwasi”, post:4, topic: 577789]
Its also worth mentioning assigning references in the inspector. This is by far the most common way I use.
do you mean the “tags” section? or can you assign references in the inspector a different way?

You can do

public IdleManager idleManager;

void GetIdleVariables
        idleManager.count += idleCount;

And drag the IdleManager in in the inspector.

1 Like

oh ok cool thanks