- Home /
How to add a value to a line of code
Very basic question here...
I have this line of code
thisCube1.gameObject.renderer.material.color = Color.red;
but I want to define the first part... eg some times I want thisCube1, another time I want thisCube2..
Coming from PHP background I just try and do something like
int i = 1;
thisCube(i).gameObject.renderer.material.color = Color.red;
But this doesnt work.. I cant just use a else statment as I am planning to generate a random number from 1 to 200 to get it to randomly control cubes.
Answer by whydoidoit · May 05, 2013 at 11:30 AM
You need to store them in an array or List and then you can use an index to access them:
using System.Collections.Generic;
Transform[] cubes;
//or
List<Transform> cubes;
Set up the cubes in the inspector for an array or both in the inspector and in the code with list. You can add to the List at runtime using Add or AddRange (and Remove too).
Then to access:
cubes[n].renderer.material.color = Color.red;
I'm sorry to be a pain, but can you give me a little more details example... or point me to a link on how I can learn to do this.
I've only 1 day in to learning this...
Transform[] cubes;
void Start () {
//assign the cubes to the array, example:
cubes = GameObject.FindGameObjectsWithTag("cube");
}
void func () {
int i = 1;
cubes(i).gameObject.renderer.material.color = Color.red;
}