Material Selector Script

I’d like to create a selection tool in the UI of my game that allows for the player to set the colour palette of every object in the game (everything uses the same material, so it would need some kind of ‘Apply to All’ bit in the code). All it has to do is have a kind of left and right selection, which will assign whichever palette comes next, letting the player choose what colour scheme they have the game in.

It sounds a bit strange, but hopefully you understand what I mean, and someone can help with how this could be coded, since I’ve found nothing online about any kind of code for selecting and instantly applying a material to objects in Unity. Thanks!

Hi there. If I’m understanding correctly what you want to do, I think you’re looking for a script like this:

    public Material yourMaterial;

    public Color color1;
    public Color color2;
    public Color color3;
    public Color color4;

    private int colourChosen;

    private void Start()
    {
        colourChosen = 1;
        yourMaterial = GetComponent<Renderer>().material;
    }

    private void Update()
    {
        if(colourChosen == 1)
        {
            yourMaterial.color = color1;
        }
        if (colourChosen == 2)
        {
            yourMaterial.color = color2;
        }
        if (colourChosen == 3)
        {
            yourMaterial.color = color3;
        }
        if (colourChosen == 4)
        {
            yourMaterial.color = color4;
        }
    }

    public void Left()
    {
        if(colourChosen > 1)
        {
            colourChosen = colourChosen - 1;
        }
    }

    public void Right()
    {
        if (colourChosen < 4)
        {
            colourChosen = colourChosen + 1;
        }
    }

I haven’t actually tested this code myself but it should work. Assign the material that your objects all share to the ‘yourMaterial’ material. You can then create some Colors and then edit these colours in the inspector. Assuming you are going to be using buttons to choose the materials, you can create an integer which determines what colour is currently selected, and add one or minus one depending on which button is pressed.

Then of course you just need to set the colour of the material depending on what the integer is.

Hopefully this is something you were looking for. :smiley: