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?

  • 3
    \$\begingroup\$ +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"? \$\endgroup\$
    – 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.

Please read the docs if you want to know additional info.

  • \$\begingroup\$ I'm not really familiar with that syntax :s lame, I know. Could you help me figure out what it means in general? I'll try it either way and let you know the result. \$\endgroup\$
    – casraf
    Jul 6 '12 at 11:11
  • \$\begingroup\$ Updated my answer. The syntax I used is standard c# generics. Read up on .net generics to become more familiar with the syntax. GetComponent is how you get references to MonoBehavior derived classes. If CubeBehavior extends MonoBehavior, Unity treats it as a 'Component' which is why you use GetComponent(); \$\endgroup\$
    – Chuck D
    Jul 6 '12 at 14:09
  • \$\begingroup\$ What do generics mean in general...heh \$\endgroup\$
    – brandon
    Jul 6 '12 at 23:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.