Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to revert material color back to what it was.

Discussion in 'Scripting' started by Quiet_Apples_Studios, Nov 11, 2020.

  1. Quiet_Apples_Studios

    Quiet_Apples_Studios

    Joined:
    Jan 27, 2020
    Posts:
    17
    Hello I'm using a scriptable object that changes the color of a meterial to a different one, but I would like to make the script automatically know what color the object was orignally and then turn it back to that.

    Is there a way to save what the color was previously and then change the material?
    I'm using scirptable objects or else I would have simply made a color vairable and called it a day
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Something like this should work:
    Code (CSharp):
    1. public class SomeSO: ScriptableObject {
    2.    public Material material;
    3.    public Color originalColor;
    4.    public Color newColor;
    5.  
    6. #if UNITY_EDITOR
    7.    private Material lastAssignedMaterial;
    8.  
    9.    private void Reset() => lastAssignedMaterial = null;
    10.    
    11.    private void OnValidate() {
    12.       if(material != null && lastAssigndMaterial != material) {
    13.          lastAssignedMaterial = material;
    14.          originalColor = material.color;
    15.       }
    16.    }
    17. #endif
    18. }
    OnValidate
    is an editor function called whenever any change to the script's inspector is made.
    This will compare if the reference to the
    material
    field has changed, and automatically set the value of
    originalColor
    to the new Material's color if so.