GetComponent w/ function trouble

I’m kind of new to Unity (and C# in general), and came across a error which I can’t explain.
In two separate files (and on separate gameobjects):

using UnityEngine;

public class MainClass : MonoBehaviour {
   
    float foo = 41f;
   
    public float FetchFoo() {
        return foo;
    }
   
    public void DoBar() {
        foo++;
    }
}

and then:

using UnityEngine;

public class OtherClass : MonoBehaviour {
   
    float foo;
   
    void Update () {
        MainClass main = GetComponent<MainClass>();
        foo = main.FetchFoo();
        main.DoBar();
        print(foo);
    }
}

This does not give me an error at main.DoBar(); but gives a NullPointerException at foo = main.FetchFoo(); Any idea why?

This belongs in the scripting section! Documentation is for questions and complaints regarding the docs. Calling @hippocoder for an airlift!

The NullRef happens ebcause there’s no MainClass attached to the same object as OtherClass, so the main variable is a null reference.

The lack of error at main.DoBar is simply due to the line not getting reached as the NullRef terminates the method. If this is just an example and you’re not getting an error somewhere else, please post some example code of that happening

1 Like

If it’s on a separate game object, you have to get that gameObject so you can use GetComponent. If you use GetComponent on the object you are on, it will only look for Components on that object. You can get that object by either dragging it onto your script from the inspector, or using GameObject.Find().

Sorry for not knowing where to put this, i’m new here!

GameObject.Find() seems to have worked, thanks!