- Home /
How to check whether a material is unique?
Hello everyone!
Hopefully this one will be quite easy. On game start I instantiate a bunch of objects on the scene. They are ready prefabs with materials. Then I would like to differentiate them a bit by drawing additional textures to them. I started with something like this:
void Update () {
if (!Input.GetMouseButton (0))
return;
RaycastHit hit;
if (!Physics.Raycast(camera.ScreenPointToRay(Input.mousePosition),out hit))
return;
Renderer renderer = hit.collider.renderer;
MeshCollider meshCollider = (MeshCollider)hit.collider;
if (renderer == null || renderer.sharedMaterial == null ||
renderer.sharedMaterial.mainTexture == null || meshCollider == null)
return;
//if( rendered.material is not unique (was not cloned yet))
{
renderer.material.mainTexture = (Texture2D)Instantiate(renderer.material.mainTexture);
}
Texture2D tex = (Texture2D)renderer.material.mainTexture;
Vector2 pixelUV = hit.textureCoord;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
Color [] c = new Color[100];
for(int i=0; i<100; i++) { c[i] = Color.red; }
tex.SetPixels((int)pixelUV.x-5,(int)pixelUV.y-5, 10,10, c);
tex.Apply();
}
This script is pretty straightforward, but what happens is that it keeps on instantiating new textures every frame. I need a way to know that certain material has already been unlinked from the shared materials and is free to be manipulated individualy.
Do you guys have any ideas? Thanks in advance!
John
Answer by robertbu · May 15, 2014 at 10:37 PM
You don't need to Instantiate() a new material. Any time you make any material change (at runtime), Unity replaces the shared material with a new material instance. So change away and you will be okay.
Does the texture get instantiated as well? $$anonymous$$y problem is that when I paint over the texture, all the object instances are being changed as their actual texture file is being modified (tex.Apply()). So even though the material gets cloned the texture itself is still assigned to the same file. Isn't that correct? And if it isn't then could you propose a simple solution to this problem? Would be greatly appreciated!
This is untrue! Though it is true for Renderer.shared$$anonymous$$aterials , not for Renderer.materials cuz this one gets instantiated.
Your answer
Follow this Question
Related Questions
Why isn't (.)sharedMaterial sharing this change to "_EmissionColor"? 0 Answers
Projector.material = sharedMaterial ? 2 Answers
How to dynamically create a cube and color it? 2 Answers
Dynamic Batching Question 1 Answer
Keep replaced materials of a Game Object even after ending the Play Mode C# 0 Answers