# Controlling a GameObject from another GameObject's script component

I'm creating a game where when starting the game, a Cube is duplicated GridSize * GridSize times when the game starts. Now, after the cubes are duplicated I want to attach a variable to them, say "Flag" which is a bool, from another script component (let's say I have a Prefab that generates the cloned cubes).

In short, I have something like this:

CreateTiles.cs : Attached to Prefab

void Start() {
createMyTiles(); // a function that clones the tiles
flagRandomTiles(); // a function that (what I'm trying to do) "Flags" 10 random cubes
}


CubeBehavior.cs : Attached to each Cube

public bool hasFlag;
// other stuff


Now, I want flagRandomTiles() to set a Cube's hasFlag property via code, assuming I have access to them via a GameObject[] array.

Here's what I've tried:

1. Cubes[x].hasFlag = true; - No access.
2. Making a function such as Cubes[x].setHasFlag(true) - still no access.
3. Initializing Cubes as a CubeBehavior object array, then doing the above - GameObjects can't be converted to CubeBehaviors - I get this error when I try to assign the Cubes into the array.

How do I do this?

• +1 Thanks for telling us what you've tried and only including the code that's important. Can you also show us the specific error messages you're getting with "No access"?
– House
Jul 5 '12 at 13:20

It looks like Cube[] is an array of GameObjects? If so, you need to reference any attached behaviors by using

 CubeBehavior cubebehavior = Cube[i].GetComponent<CubeBehavior>();
cubebehavior.hasFlag = [yourvalue];


The syntax above uses the generic signature for GetComponent(); If this syntax is difficult to understand, you can also use GetComponent("T") as T which does not return you a strongly typed component.