- Home /
accessing gameObject script from an array
Sorry if this is too obvious, I'm still trying to learn how to scipt. Here's the problem I'm having. I have three boxes in the scene called box1, box2, box3. These boxes are in a gameobject array variable within a script that's attached to the camera.
Now each of these boxes have a script attached to them that switches a bool to off if I mouse over the box.
My question is, how do I access this script that's attached to these boxes through the script that's attached to the camera and within the array that these boxes are held at. I usually use a GameObject.Find to find info for one object, but never had to do it within an array. Any help would be great thanks!
Answer by testure · Jul 17, 2011 at 06:46 AM
So long as you have a reference to the gameobject or transform (which it sounds like you have with your mouseover functionality), you can simply use GetComponent to get a reference to the component/script you want:
http://unity3d.com/support/documentation/ScriptReference/Component.GetComponent.html
Answer by DaveA · Jul 17, 2011 at 07:22 AM
In your camera script, probably have
var boxes : GameObject[]; // assign your boxes in inspector or code
... some function..
var ms : MyScript = boxes[1].GetComponent("MyScript");
ms.myBool = false; //or whatever
Note you can pre-fetch the components of those boxes in a Start script so you don't have to GetComponent each time.
Answer by YikYikHeiHei · Jul 17, 2011 at 09:13 AM
This script can called any tag"box" in gameObject script.
// Disable the spring on all HingeJoints
// in this game object
var boxes : GameObject[];
var boxScript : boxScript;
function Start ()
{
boxes = GameObject.FindGameObjectsWithTag("box");
for (var i : int = 0; i < boxes.Length;i++)
{
boxScript[i] = boxObject[i].GetComponents("YourScript");
boxScript[i].yourBoolean = false;`
}
}