Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Unity 2020 LTS & Unity 2021.1 have been released.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    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).