- Home /
How to clone a material in each instantiated prefab as Unique temporary material.
Hello guys, i tried everything to instantiate a material into a clone of a prefab. I tried to attach a script into a Car Prefab who can randomize colors, in each cloned prefab i need to put a new material or a temporary material with one color each.
I tried to change the material who references the prefab but all the cars change to the same color in each start of my coroutine.
private void RandomCarColor(){
rlColor = carColor[randomColorNumber];
string shaderText =
"Shader \"Alpha Diffuse\" {" +
"Properties { _Color (\"Main Color\", Color) = (1,1,1,0) }" +
"SubShader {" +
" Tags { \"Queue\" = \"Transparent\" }" +
" Pass {" +
" Blend One One ZWrite Off ColorMask RGB" +
" Material { Diffuse [_Color] Ambient [_Color] }" +
" Lighting On" +
" SetTexture [_Dummy] { combine primary double, primary }" +
" }" +
"}" +
"}";
renderer.material = new Material( shaderText );
renderer.material.color = rlColor;
clonedMaterial.color = rlColor;
What help i need: How to, assign a temporary material for each instance i spawn from this original car object.
I can saw the new material(Instantiated) in the inspector but it not assigned the color cars dont change for a unique color each one. Someone can help? Thanks.
Answer by Stormizin · Apr 17, 2012 at 09:04 PM
I did, something more easily, i opened the maya modeling, and change my car model, i combine all the polygons into one, imported to the unity again and created a new car prefab puting the Unique Mesh into the prefab, then i created a script who randomize the color at the Start() function. Thanks a lot bro for your time.
Answer by Piflik · Apr 17, 2012 at 05:06 PM
When you alter a property of a material during runtime, Unity automatically creates a clone of the material and uses it for the current prefab/clone only. The other objects in the scene using the same material won't be affected, unless you use:
renderer.sharedMaterial
Answer by Lttldude · Apr 17, 2012 at 03:57 PM
I think you may be over complicating this or I don't fully understand.
If you are trying to just create a new color for each car, then do something like this:
var prefab : GameObject;
var colors : Color[];
function Start()
{
for(var i=0; i<5; i++)
{
var instPrefab : GameObject = Instantiate(prefab, Vector3(5*i,5*i,0), Quaternion.identity);
instPrefab.renderer.material.color = colors[Random.Range(0, colors.Length)];
}
}
Tell me if this doesn't help.
Answer by bombsquare · Feb 06, 2016 at 02:30 PM
You maybe looking for procedural materials that can be created at runtime?
http://docs.unity3d.com/Manual/class-ProceduralMaterial.html
Your answer
Follow this Question
Related Questions
Material Switching Upon Instantiation. over my head 0 Answers
Checking if object intersects? 1 Answer
Material doesn't have a color property '_Color' 4 Answers
Missing Material in AssetBundle Prefab 3 Answers
Cannot Assign Material To Object 1 Answer