buttonactive is a boolean set in class onclick.
When I hit play in Unity, all I get is this:
NullReferenceException: Object reference not set to an instance of an object
Goal.Update () (at Assets/Goal.cs:45)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
I tried many things, but nothing worked out for me
First of all, thx for your answer!
They aren’t on the same object, onclick is attached to a Canvas while this script is attached to a 3d model. Do they have to be attached to the same gameobject or is there a way to do it like this?
GetComponent searches for a component attached to the same GameObject that the script is.
If you want to get a component from a parent or child GameObject, use GetComponentInParent and GetComponentInChildren respectively.
Another option is to just make your component reference public and drag the reference to it from the inspector window:
public class Example : MonoBehaviour {
public OnClick onClick; //Assign the reference from the inspector window.
void Update() {
if(onClick.buttonactive && i == 0) {
i++;
}
}
}
Finally, some things to recommend:
Class names in your scripts should start with a capital letter by convention.
GetComponent should not be called every frame as it is an expensive operation. Instead, cache the component reference. For example:
public class Example : MonoBehaviour {
private OnClick onClick;
void Start() {
//Caching the reference to the OnClick component.
onClick = GetComponent<OnClick>(); //Can use GetComponentInParent or GetComponentInChildren if needed.
}
void Update() {
if(onClick.buttonactive && i == 0) {
i++;
}
}
}
Whoops, I misread your last post thinking it was a parent component you were trying to reference.
But yes it is possible, there are lots of of ways to get a reference to a component. Your first best bet will be this method:
Making the component reference public allows you to select any component of the same type in the scene or the Assets folder and drag it into your script from the inspector window.
Other than that, here are all the other ways you can reference a component:
GetComponent selects the first instance of a component attached to the same GameObject.
GetComponents selects all instances of a component attached to the same GameObject.
GetComponentInParent searches all parents of a GameObject for the first instance a component.
GetComponentsInParent searches all parents of a GameObject for all instances a component.
GetComponentInChildren searches all child GameObjects for the first instance of a component.