- Home /
How to set color to gameObject respective to below coding?
var prefab : GameObject; var numberOfObjects = 10; var radius = 5;
function Start () { for (var i = 0; i < numberOfObjects; i++) {
var angle = i * Mathf.PI * 2 / numberOfObjects;
var pos = Vector3 (Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
Instantiate(prefab, pos, Quaternion.identity);
} }
Several comments on your question. First off, please edit your post so that your code tags fit around the entire code block. This tool can be found via the button that reads "101010".
Also, don't just put your question in the header. Please put the question and a little more relevant information in the actual question body.
I would recommend changing this title to something like "Setting Prefab Color Programmatically"
Answer by Lovrenc · Jul 29, 2013 at 12:50 PM
renderer.material.color = yourColor
i have 10 gameobjects , each of gameobject should have diffrent color.how could i do this pls some one help me?
Answer by brandonsbarber · Jul 29, 2013 at 03:26 PM
Assuming you already know all of the colors you need, I would just make an array of Color
objects (`Color[]`) that is equal in length to the number of objects you need.
Set all of these colors (either with an initializer list, a loop, or manually). Then, inside of your loop in Start
, you need to change a few things. First off, save the result of Instantiate
to a GameObject
. To do this, change your line to save it to a GameObject
variable.
var myObject : GameObject = Instantiate(prefab, pos, Quaternion.identity);
Essentially, this tells myObject
that it is a GameObject
, and then sets it to be whatever you just created. After this, simply call
myObject.renderer.material.color = myColorArray[i]; //myColorArray is the previously mentioned color array
and you should be all set.