- Home /
Change material inside instanced prefab, gameobject.renderer is NULL
I use an xml file to keep track of which prefabs I want to assign to which gabeobjects, which I instantiate at runtime, so the level gets generated dynamically.
So I load the prefabs with this line of code into my asset libary:
GameObject roomCornerTile = Resources.LoadAssetAtPath<GameObject>(roomCornerTilesPaths[i]);
I set the GameObject var of one of my objects with this line of code later on:
return GameObject.Instantiate(roomCornerTile) as GameObject;
After that, I perform transformations on it to place it in the actual world. Note, that the prefab and materials are loaded like it should and everything works as intended.
Now I want to replace the Material channel 0 which contains a transparent material by prefab definition so I can set it to a colored material according to my needs. This happens here:
blueprintValidMaterial = Resources.Load ("Materials/TestMaterials/BlueprintValidMaterial") as Material;
tile.mesh.renderer.materials[0] = blueprintValidMaterial;
Problem is, that exactly at this point, the renderer is NULL and I can't modify any materials or assign new ones.
Question:
How do I have to instantiate a prefab and modify it so I can change materials from an instanced prefab gameobject?
Here you can see the inspector of the prefab and the instanced gameobject. Note that the instanced object has a renderer in the inspector, but is missing the 2nd material channel.
I could not come up with a solution, please help!
Answer by Jeff-Kesselman · May 20, 2014 at 12:16 AM
what is "tile" in the above code?
If its the prefab then no, you can't do that. What you need to do is Instantiate the prefab and then change the material on the instance.
Tile is my own class which has an attribute of type GameObject which is called mesh. This is supposed to be the visible gameobject of this tile which is part of a huge grid.
How is the mesh field getting set? If you are stuffing a prefab into it, see above.