Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
3  
+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"? –  Byte56 Jul 5 '12 at 13:20

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
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. –  Chen Asraf Jul 6 '12 at 11:11
    
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(); –  Rubber Mallet Jul 6 '12 at 14:09
    
What do generics mean in general...heh –  brandon Jul 6 '12 at 23:35
    
Works like a charm, thanks! –  Chen Asraf Jul 7 '12 at 2:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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