Search Unity

Change material to default

Discussion in 'Getting Started' started by iliustracijos, Jan 19, 2016.

  1. iliustracijos

    iliustracijos

    Joined:
    Jan 19, 2016
    Posts:
    4
    Hi,

    For example i have scene with a lot of cubes and different materials applied to them.
    Mat01, Mat02, Mat03........

    I'm inserted the Button witch takes an another Material from Resources folder and applied to these cubes.

    Material newMat = Resources.Load("Material", typeof(Material)) as Material;
    Cube[1....X].GetComponent<Renderer> ().material = newMat;

    Question is : How can i get back to default assigned materials, that every cube has his own Mat01... again. ?

    I'm tryed to save every scene object cube in new Array[] to save material property, but problem is when i press the Button materials change in new Array[] as well. How to save every scene object and his material property for restore in late.

    Anyone know ?
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    It sounds like you're saving references to the cubes (perhaps as GameObject?). But what you're changing is the material property of the renderer on the cube. So, keeping just the cube references wouldn't help.

    You need to instead store the Material. I would approach this by making a script that goes on each cube, that saves the material (via GetComponent<Renderer>().material) in a property. Then this script can have a public Restore method, that applies the saved material back to the renderer. You can call the Restore method on all cubes whenever that's wanted.
     
  3. iliustracijos

    iliustracijos

    Joined:
    Jan 19, 2016
    Posts:
    4
    Thanks JoeStrout for reply, but i didn't get it, where to save materials and assignments of all GameObjects ? new Array ?
    And how can it looks like public Restore method in C# ? Maybe can you show a little example ?
     
  4. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Sure, this is off the top of my head, but should be approximately right...

    Code (CSharp):
    1. public class MaterialSaver : MonoBehaviour {
    2.     Material originalMat;
    3.    
    4.     void Start() {
    5.         originalMat = GetComponent<Renderer>().material;
    6.     }
    7.    
    8.     public void Restore() {
    9.         GetComponent<Renderer>().material = originalMat;
    10.     }
    11. }
    Put this on each of your cubes. Now just call GetComponent<MaterialSaver>().Restore() on all of your cubes when you want to restore the original materials.
     
    radiantboy, Vulth01, Curipoc and 3 others like this.
  5. iliustracijos

    iliustracijos

    Joined:
    Jan 19, 2016
    Posts:
    4
    Finally i did it ! Thanks JoeStrout for your example it was handy.
     
    JoeStrout likes this.