- Home /
how do you switch between colors on the same gameobject?
Hey I'm new to unity and currently in school for programming. Right now were doing a project where we make a cube and with the press of certain keys make it change to select colors. I have the code for setting the color and for targeting the gameobject. but what i can't figure out is how to make it change color when i press the button for a different color. help would be appreciated... or even just some advice. i searched online but all my searches just dance around the subject
Edit : my code so far
var target : GameObject;
var pick;
function Start () {
switch (pick){
case 'a': target.renderer.material.color = Color.blue;
break;
case 's': target.renderer.material.color = Color.cyan;
break;
case 'd': target.renderer.material.color = Color.green;
break;
case 'f': target.renderer.material.color = Color.yellow;
break;
case 'q': target.renderer.material.color = Color.red;
break;
case 'w': target.renderer.material.color = Color.magenta;
break;
case 'e': target.renderer.material.color = Color.grey;
break;
case 'r': target.renderer.material.color = Color.white;
break;
}
}
function Update () {
var pick = Input;
}return pick;
If you submit your code when asking a question, we can see what you are trying to do and help from there.
Answer by AlucardJay · Apr 22, 2013 at 08:33 PM
var currentColour : int = 0;
var maxColours : int = 4;
function Update()
{
if ( Input.GetMouseButtonDown(0) )
{
currentColour ++;
if ( currentColour >= maxColours )
{
currentColour = 0;
}
switch( currentColour )
{
case 0 :
// change colour to the first colour
break;
case 1 :
// change colour to the second colour
break;
case 2 :
// change colour to the third colour
break;
case 3 :
// change colour to the fourth colour
break;
}
}
}
Does this mean I just did your homework?
not necessarily.... i'm mostly working on getting it to sayif i press a it will turnt he cube blue and if i then hit w it will change to red... i think the main issue i been having is getting the system to read the input of the key
Actually, your code is a mess. Exa$$anonymous$$e the logic, read it as a computer would.
Start happens only once (without going into detail, keeping it simple)
var pick = Input; : see my above post
}return pick; : you cannot execute commands outside of functions
So, structure it just like my example. Get your input, then switch on that input in the Update function
and rest assured you didnt do my home work for me but you did point me in the right direction
Your answer
![](https://koobas.hobune.stream/wayback/20220613100837im_/https://answers.unity.com/themes/thub/images/avi.jpg)