How can i change a material/color to an object from the main menu settings scene

Viewed 24

The title is pretty self explanatory. I have in the main menu scene a settings tab and in there i want to add a toggle that when enabled it changes the color or material from an object in a different scene. I did add the toggle but i have no idea what i should write in the script attached to it and how the script is going to be global. If somebody could help me please answer bellow.

2 Answers

You can make an object persist through scenes loading/unloading with the DontDestroyOnLoad(GameObject) method, and have that object have a script which contains your Material information.

Simply:

  1. Make a new script with a Material variable (or an integer, anything to signify the value)
  2. In the Start, Awake, OnEnable, etc, use DontDestroyOnLoad(gameObject);
  3. Add the script to an object in your Main Menu scene

You can then use that variable in the new persistent GameObject's script to change the material.

Example implementation:

using UnityEngine;

public class GlobalSettings {

    //instance, so we can get this object statically
    public static GlobalSettings instance;

    [SerializeField] private Material[] choosableMaterials;
    private int materialIndex;

    //Property to return the current material
    public Material CurrentMaterial => choosableMaterials[materialIndex];

    //Set our instance variable
    public void OnEnable() {
        instance = this;
    }

    //OnClick method for your button. Implement however you're changing the materials.
    public void MaterialButtonPress(int value) {
        materialIndex = value;
    }
}

and in the scripts that you want to be able to access this value...

//start of class...

    public void Start() {
        Renderer renderer = GetComponent<Renderer>(); //change to whatever renderer type you're using
        renderer.material = GlobalSettings.instance.CurrentMaterial;
    }

//rest of class...

I have similar thing in my game where I let players choose wrestler's mask's color. You can change texture of material by using Material.mainTexture. check out the docs here You can also change color using Material.color. docs

Good luck

Related