Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Prefab creation with variant materials (in editor script)

Discussion in 'Prefabs' started by crawfis, Dec 31, 2020.

  1. crawfis


    Jan 30, 2014
    I am trying to develop some Editor-based PCG tools. I call
    to create a new instance as follows:
    Code (CSharp):
    1.             GameObject newGameObject = UnityEditor.PrefabUtility.InstantiatePrefab(prefab) as GameObject;
    Once the new game object is created, I want to modify the color of the material. I have tried the three options below and they all have problems (Note, this is by clicking a button in the editor - NOT runtime or during Play). I have 3 possible work-arounds (below), but wanted to see if I am doing something wrong.

    Code (CSharp):
    1.         public async Task ApplyAsync(GameObject prefab)
    2.         {
    3.             Renderer renderer = prefab.GetComponent<Renderer>();
    4.             if(renderer != null)
    5.             {
    6.                 Color newColor = randomColor.GetNext();
    7.                 // Option 1: Editor give error - use sharedMaterial. Prefab materials are broken when dragged into folder.
    8.                 //renderer.material.color = newColor;
    9.                 // Option 2: All prefabs have the same color.
    10.                 //renderer.sharedMaterial.color = newColor;
    11.                 // Option 1: Prefab materials are broken when dragged into folder. New materials are lost.
    12.                 var newMaterial = new Material(renderer.sharedMaterial);
    13.                 newMaterial.SetColor("_Color", newColor);
    14.                 renderer.material = newMaterial;
    15.             }
    16.             await Task.CompletedTask;
    17.         }
    Hopefully someone has an easy fix to this problem. I have searched quite a bit and cannot find a solution. Some possible work-arounds:
    1. Explicitly Save the materials (even duplicates) somehow. I am looking at 1000's of instances.
    2. Use a predefined Material palette and set the material to that.
    3. Add a script to the prefab that will change the color at runtime (will not be able to see the results in the editor at design time though).
  2. WidmerNoel


    Jun 3, 2014
    I am having this issue as well. The API seems way too ambiguous and complicated to figure out how this should be done.