Apply multiple materials using the same key

hi! I like to apply differents materials, like colors one by one on an object by pressing the same key, I found some C# scripts on google but they are using differents keys :(.
for example : my object who has the material01 on it, by pressing a key (spacebar for example) it will have material02 on it, and by pressing spacebar again, material03 on it and with spacebar again (i know that a lot of spacebar :smile:) it will return to the material01,… and etc… .

Please help me, i’m a total noob at programming!!!
Ps: Sorry for my bad English.

You found some code using different keys?

What keys are you trying to use? You should be able to just change the key they are using. Try it, and if you can’t get it to work with they key that you want, then post the code that you tried here. Please be sure to use code tags if you do end up needing to post your code :slight_smile:

Regards,
Rob

i found this on google

using System.Collections;
using UnityEngine;

public class color : MonoBehaviour {

// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {

if (Input.GetKeyDown(KeyCode.R))
{
gameObject.GetComponent().material.color = Color.red;
}
if (Input.GetKeyDown(KeyCode.G))
{
gameObject.GetComponent().material.color = Color.green;
}
}
}

i change the KeyCode.G to KeyCode.R:

if (Input.GetKeyDown(KeyCode.R))
{
gameObject.GetComponent().material.color = Color.red;
}
if (Input.GetKeyDown(KeyCode.R))
{
gameObject.GetComponent().material.color = Color.green;
}
}

but the object become green without became red before and i don’t know how to change it to red after becoming green. any help? please…

In the future, please use tags around your code snippets. More info on this here:

So, now what you need is a way to check which color is currently active. What’s happening with your code at the moment is that when “R” is pressed, it changes the color to red and then changes the color to green.

You can remove the second if statement and inside of your current if statement, write another that checks which color is active, and sets the other.

example:

using System.Collections;
using UnityEngine;

public class color : MonoBehaviour {

  public bool isRed; //We will use this to tell us color is red

  // Update is called once per frame
  void Update ()
  {
    if (Input.GetKeyDown(KeyCode.R))
    {
      if (isRed)
      { //color is red, lets make it green
        gameObject.GetComponent<Renderer>().material.color = Color.green;
      }
      else { //color is not red, so lets make it red
        gameObject.GetComponent<Renderer>().material.color = Color.red;
      }
    }
  }
}

There are many different ways to do this, but this will at least give you a basic start :slight_smile:

this should also work

using System.Collections;
using UnityEngine;

public class color : MonoBehaviour
{
   
    public Material[] materials; //assign materials to this in the editor
   
    int index;
   
    Renderer renderer;
   
    void Start()
    {
        renderer=GetComponent<Renderer>();
    }
    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            index++;
            if(index==materials.length)
                index=0;
            renderer.material=materials[index];
        }
    }
}

Thanks for helping me and sorry for the delay of my answer, i try it and my problem is at the begining my gameobject is red when i use the script (and press R) is becoming green (that’s cool) but how can i make it switch material by pressing R again. I’m a total noob in programming so i try this:

using System.Collections;
using UnityEngine;

public class color : MonoBehaviour
{
    public Material Red;
    public Material Blue;
    public Material Green;
    public bool isRed; //We will use this to tell us color is red
    public bool isGreen;
    public bool isBlue;
// Update is called once per frame
  void Update()

{

   if (Input.GetKeyDown(KeyCode.R))

   {

     if (isRed)

     { //color is red, lets make it green
     gameObject.GetComponent<Renderer>().material = Blue;

     }

     else { //color is not red, so lets make it red
      gameObject.GetComponent<Renderer>().material = Red;
     }

    }
        if (Input.GetKeyDown(KeyCode.R))

        {

            if (isBlue)

            { //color is red, lets make it green
                gameObject.GetComponent<Renderer>().material = Green;

            }

            else
            { //color is not red, so lets make it red
                gameObject.GetComponent<Renderer>().material = Blue;
            }

        }
        if (Input.GetKeyDown(KeyCode.R))

        {

            if (isGreen)

            { //color is red, lets make it green
                gameObject.GetComponent<Renderer>().material = Red;

            }

            else
            { //color is not red, so lets make it red
                gameObject.GetComponent<Renderer>().material = Green;
            }

        }
    }
}

but when i start to play, the gameObject become green without having been blue, and stay green. i would like it to become, by pressing R, Red to Blue, and when i press R again Blue to Green, Press R again Green to Red, and so on…

thanks in advance.

thanks for helping me but i’m a total noob at programming can you rewrite it with giving me an example

his entire post is the example… its a basic “cycle through the members of an array”. It’s also pretty much what you asked for in the OP. @3zzerland seems to be taking you off on a tangent trying to “fix” code you found that doesn’t do what you were looking for.

What I’m trying to do is help him understand the code he is using. From the code he posted (in both snippets), I’m not actually sure he wants to change materials at all. It looks to me like he really just wants to change the color.

If you want to change the material and not the color at all, then look a little closer at what jaasso posted.

look at the first three posts again; you asked him what he found, he pasted in what he’d found on google. What he found doesn’t do what he said in his example in the OP.

that’s a “cycle through limited selection of options” aka an array

It’s possible that what he wants to do is change colors and its possible that he thought he needed to change materials to do that. Anyway, why am I wasting efforts bickering?

@yamacha

if (Input.GetKeyDown(KeyCode.R)) {}

Anything that should happen when you press ‘R’ should happen between the {} braces of this statement. You can do multiple things inside this one statement without having to have this statement multiple times.

Now, if you want to change the actual material and not just the color, then you need to gather a list (or array) of the materials you want it to change to. That’s what @jaasso was showing you:

public Material[] materials; //assign materials to this in the editor

The [ ] indicates this is an array of type Material. When you assign his script to your game object, you will see in the Inspector a ‘Materials’ item that you can assign multiple materials to.

His code would replace yours entirely if you want to change materials and not colors.

If you have questions about what a line in his code is doing, please feel free to ask so we can help you with the parts you are unsure of.

fair point :slight_smile:

1 Like

Thanks for taking the time to explain me the code, yes i would like to change the color of my gameObject with just pressing one key, and do an cycle (press (R)) red to blue (my object becomes and stays blue), press (R) blue to green(my object becomes and stays green), press (R) green to red (my object becomes and stays red), red to blue, blue to green… and so on.
Every time i press the key (R) the color of my gameObject changes, if i don’t press (R), the last colour of the gameObject remains and doesn’t change until i press (R) again.
ex: the gameObject is red i press (R) it becomes and stays blue until i press (R) again.
Can you help me :(? thanks a lot!
Sincerely yours.

I’m going to walk you through editing @jaasso code snippet to do what you want.

The array that he has you can change into an array of type Color and rename it colors:

public Colors[] colors;

In the inspector, you would then choose the colors you want to cycle through, or you can populate this with code in the Start() function if you only want to use the 3 colors and never change them later. For now, I recommend just doing it in the inspector.

The int index is being used to identify which color in the array is going to keep track of the index we want to update the color to.

The Render is the component that holds the material. In his code, he is caching our GetComponent call in the Start() function so that all future references don’t cost us a look up call to find that component (we stored it in a local variable so we already have it found).

In his update function, you have the Input conditional statement checking to see if ‘R’ has been pressed. When it is pressed, we want to execute the code inside the {} braces.

index++;
if(index==materials.length)
  index=0;

index (remember is the variable we use to track which color we want to change to) gets incremented here in this snippet with the ++. Then, the if condition checks to see if the index is the same length as the array variable we created. Remember, we are changing materials to colors, so we need to fix the name of the array.
“.length” returns the amount of variables in our colors array. We want to cycle through them, so when we get to the end we need to reset our index back to 0. That’s what the conditional is doing in his code.

renderer.material=materials[index];

This line changes the material. We need to update this line to just change the color of the existing material to the color from our colors array index. since our GetComponent is cached in the variable ‘renderer’ we can make appropriate use of it instead of what we were doing before.

renderer.material.color = colors[index];

See if you can piece all that together and show me what you come up with :slight_smile:
Regards,
Rob

using UnityEngine;
using System.Collections;

public class tryColors : MonoBehaviour {
    public Color[] colors; //assign colors to this in the editor
    public Color[] Red;
    public Color[] Blue;
    public Color[] Green;

    int index;

    Renderer renderer;

    void Start()
    {
        renderer = GetComponent<Renderer>();
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {

            index++;
            if (index == colors.length)
                index = 0;
            renderer.material.color = colors[index];
        }
    }
}

Is it something like this? i have this error

Error CS1061 ‘Color[ ]’ does not contain a definition for ‘length’ and no extension method ‘length’ accepting a first argument of type ‘Color[ ]’ could be found (are you missing a using directive or an assembly reference?)

Could you give me an concrete example with two colors maybe, to understand how to write the script.
Best regards.

It’s Length, not length (capitalization)

Colors[ ] colors is an array of colors, meaning that you can add all your color options to that (from the inspector). You don’t need Colors[ ] Red/blue/green.

As KelsoMRK said, Length should be capitalized. That was my typo earlier.

Other than that, your code looks correct. So attach that to the game object that you want the colors to change on, then click on that game object and look at your inspector. You will need to select colors from the inspector view for your array.

thanks KelsoMRK.
So i rewrite the code like this, base on your comments:

using UnityEngine;
using System.Collections;

public class tryColors : MonoBehaviour {
    public Color[] colors; //assign materials to this in the editor

    int index;

    Renderer renderer;

    void Start()
    {
        renderer = GetComponent<Renderer>();
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            index++;
            if (index == colors.Length)
                index = 0;
            renderer.material.color = colors[index];
        }
    }
}

thanks a lot guys, now it’s working!!! you are my saviors!!!

i have just one question how can i populate the 3 colors in the code instead of the inspector?

1 Like
Color[] colors = new Color[3] { Color.red, Color.blue, Color.green }

Many thanks for the help. have a nice day!