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

Prefab creation with variant materials (in editor script)

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

  1. crawfis

    crawfis

    Joined:
    Jan 30, 2014
    Posts:
    114
    I am trying to develop some Editor-based PCG tools. I call
    PrefabUtility.InstantiatePrefab
    to create a new instance as follows:
    Code (CSharp):
    1.             GameObject newGameObject = UnityEditor.PrefabUtility.InstantiatePrefab(prefab) as GameObject;
    2.  
    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.         }
    18.  
    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

    WidmerNoel

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