Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Check if material is temporary at runtime.

Discussion in 'Scripting' started by nporaMep, Oct 11, 2015.

  1. nporaMep

    nporaMep

    Joined:
    Oct 31, 2014
    Posts:
    33
    I have 1000 red spheres rolling with sharedMaterial.
    Then 1 of them need to start fading into green over time.

    So before I start to change color I need to create new material and assign it to that concrete sphere.
    In all next ticks I want to change that assigned material's color.

    I can do it in editor with:
    if (!UnityEditor.EditorUtility.IsPersistent(MeshRenderer.sharedMaterial))

    How can I get same effect in runtime?

    Or what is correct approach here? I don't want to create 1000 instances of same red material.

    Code (CSharp):
    1.         Color targetColor;
    2.         MeshRenderer renderer;
    3.         void Update() {
    4.             if (renderer.sharedMaterial.color == targetColor) return;
    5.  
    6.             var material = new Material(renderer.sharedMaterial);
    7.             Destroy (renderer.sharedMaterial);
    8.             renderer.sharedMaterial = material;
    9.             renderer.sharedMaterial.color = Color.Lerp(renderer.sharedMaterial.color, targetColor, Time.deltaTime);
    10.         }
    This code creates Material every frame.
    Also it throws first time on Destroy, because it can't destroy asset material.
    If I don't create it then I change color over all spheres.
    If I use .material then it creates new material also as I got from documentation.
     
    Last edited: Oct 11, 2015
  2. Thomas-Mountainborn

    Thomas-Mountainborn

    Joined:
    Jun 11, 2015
    Posts:
    489
    What's keeping you from setting the .material of the special sphere once to a different material, and then lerp the color on that material? All other spheres will still be using the shared red material.
     
  3. nporaMep

    nporaMep

    Joined:
    Oct 31, 2014
    Posts:
    33
    To do this I need additional boolean like
    bool isMaterialUnmodified = true;

    then
    if (renderer.sharedMaterial.color != targetColor && isMaterialUnmodified) {
    renderer.material = new Material(renderer.sharedMaterial);
    isMaterialUnmodified = false;
    }

    Is it right?