Hello, I have a editor script that adds a clone of a prefab with several children objects to the scene. What I need the script to do is to replace the materials of the objects with duplicate materials so that I can edit them independently. This will save me from having to manually create materials and assign the custom shader to each material for the child objects of each prefab I use. I want to be able to edit the settings, textures, etc. of each prefab without changing all the others in the scene. Perhaps I’m going about this the wrong way as I’m fairly new to unity but here’s what I have so far (I edited the names to make it more generic):
using UnityEditor;
using UnityEngine;
public class MyMenu : MonoBehaviour {
[MenuItem("MyMenu/Add Prefab")]
static void AddMyPrefab()
{
GameObject myTestPrefab = (GameObject)AssetDatabase.LoadAssetAtPath("Path/To/My/Prefab.prefab", typeof(GameObject));
GameObject myTestObj = Instantiate(myTestPrefab);
GameObject[] prefabChildren = new GameObject[myTestObj.transform.childCount];
for (int i = 0; i < myTestObj.transform.childCount; i++) { prefabChildren = myTestObj.transform.GetChild(i).gameObject; }
GameObject childOne;
GameObject childTwo;
GameObject childThree;
// Need to create new materials and assign to each child object in the if statement, preferably a duplicate of the materials already attached.
foreach (GameObject prefabChild in prefabChildren) {
if (prefabChild.name == "ChildOne") { childOne = prefabChild; }
else if (prefabChild.name == "ChildTwo") { childTwo= prefabChild; }
else if (prefabChild.name == "ChildThree") { childThree = prefabChild; }
}
}
This code instantiates prefabs in the scene fine but I cannot figure out how to create a new material to assign to the child objects. Most of the solutions I’ve googled are either for dealing with materials at runtime or I can’t get anywhere with them. I’m thinking maybe I’m going about this the wrong way.
Any suggestions about how I might do this would be greatly appreciated.
Thanks!