How do i change the game objects color with script.

How do i change the “Main color” of the game object with the tag “enemy” with jscript. Sorry about the newby question as i have just started learning unity no longer than a month ago. Been stuck on this for a while.

This is the code that i tried.

function OnGUI () 
{
	if(GUI.Button(Rect(10,10,100,40), "Enemy Color"));
	{
		tag.enemy.transform.renderer.material.color = Color.red;
	}

}
  1. You have a semicolon right after your if statement. When you do that, your if statement will execute an empty statement. See, usually, an if statement follows these two formats:

    if (boolean_condition)
    statement;

    if (boolean_condition)
    {
    statement1;
    statement2;

    statementN;
    }

As you can see, the statement part can either be a single statement or a block statement. An empty statement (when there is only a semicolon “;”) falls into the first category, therefore the block after your if statement is not seen as part of the if statement.

  1. If you are attaching this script to one enemy object, you can directly refer to the renderer in the script:

    renderer.material.color = Color.red;

  2. If this script is meant to look for all objects that have the “enemy” tag, you can use this function to get an array of GameObjects with a certain tag:

    var enemyObjectArray = GameObject.FindGameObjectsWithTag (“enemy”);

You can then act on this array with a for loop:

for(var i = 0; i < enemyObjectArray.length; ++i)
{
    enemyObjectArray*.renderer //... do the rest here*

}

There’s one small problem with the posted code: a transform is a component, just like a renderer! But fret not; the answer is easy:

enemy.renderer.material.color = Color.red;

GameObject has a Renderer, which contains a Material. Inside the Material is a Color property that can be altered (for most types of shader, that is. There are some shaders that do not have a color property!)

Thanks alot! i was making an option screen GUI button that changes the color of the enemy every time you press it.