- Home /
Accessing Monobehaviour classes on other objects
I have created a small class with a variable that I wanted to attach to an empty game object. I had it inherit from Monobehaviour because I wanted to be able change the variable value from the inspector.
Since I can't use constructors on classes that are derived from that, how do I gain access to that variable on that object (or any object with one) from another script?
I'm sure this is probably an easy answer, and I just don't know how to ask the question in Google to get the correct response
Every day. Every damn day this question is asked at least once.
To be fair, at least the question asker is aware of the nature of this question. Putting "unity access variable on another script" or similar into Google will get plenty of results. So basically just ask your question on Google and be sure to put "unity" in there.
Answer by Eric5h5 · Aug 03, 2013 at 09:33 PM
Thanks for the kind reply Eric. Next time, I'll be sure to do more research and solve the problem myself, so I don't offend others. I know that I may be asking some questions that probably didn't need to be asked, but I will try to update my comments so that people will see this in future searches.
They have a short tutorial on this at this web link. http://unity3d.com/learn/tutorials/modules/beginner/scripting/getcomponent
For me at least, I found this to not work. They attach the script to a gameobject, but they don't find the object. I don't know why it seems to run in the video opposed to my test scene.
I had to type the former opposed to the latter.
yetAnotherScript = GameObject.Find("Cube").gameObject.GetComponent<YetAnotherScript>();
yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>();
The latter gave me Null References for some reason. Just wanted to post this in case other people come searching for this.
If you get a null reference error with that, it's because otherGameObject wasn't defined.
In the script on the tutorial site, they have
public GameObject otherGameObject;
private YetAnotherScript yetAnotherScript;
In their tutorial, I don't see otherGameObject being assigned a specific object, so I figured that much, that it was just a null object. Although, in the video it runs when they click play.