- Home /
Accessing Variables within another gameobject's script
So far I have two game objects, one which has to change one of the variables in the first one's script. So far, I have this,
private var firstObject : GameObject;
function Start () {
firstObject = GameObject.Find("yellowBarrel");
firstObject.RollingLogic.values = 4;
}
and in the other script...
public var values: int;
[...]
(The script containing the variable is called RollingLogic) I know the yellow barrel was found because I can apply a transformation to it, I just can't figure out how to access it's variables. Thanks for any help!
Answer by JoaquinRD · Aug 17, 2013 at 01:21 PM
The problem is that your firstObject variable is defined as a GameObject. In order to access the values in your RollingLogic script, you need to store that instance of the script in a variable of type RollingLogic. To do this, first find the GameObject, then get the RollingLogic Component from that GameObject. For example:
private var firstObject : RollingLogic;
function Start() {
firstObject = GameObject.Find("yellowBarrel").GetComponent(RollingLogic);
firstObject.values = 4;
}
Getting the following error with this code.
BCE0018: The name 'RollingLogic' does not denote a valid type ('not found').
Well, jdellis23 - does the GameObject called "yellowBarrel" in your scene have the script titled "RollingLogic"? That is how this snippet of code works, find object called x, with component y and save it to a variable z. Then you are able to edit a variable on y's script.
Yes the GameObject has the script attached to it as a component.
Answer by ArkaneX · Aug 17, 2013 at 01:18 PM
If RollingScript is attached to yellowBarrel, than it is one of yellowBarrel's components. You have to access it using GetComponent method.
Getting the following error with this code.
BCE0018: The name 'RollingLogic' does not denote a valid type ('not found').
RollingLogic is the name of the script. Write your script name here ins$$anonymous$$d, which you have attached to the gameObject you want to access.