- Home /
How to independently change textures on clones in C#?
I'd like to have a prototype object, which I clone at runtime (possibly many times) and then change the texture on each one independently. My early experiments were in JavaScript, but now I'm moving to C# for easier multidimensional arrays.
In JavaScript, this works fine:
panel = Instantiate(panelPrototype, Vector3(0,-0.5,0), Quaternion.Euler(0,0,180));
panel.renderer.material.mainTextureOffset = Vector2(col/16.0, (15-row)/16.0);
I can call this multiple times with different row and col values, and each one gets a unique look. But when I try to do the same thing in C#:
panel = (GameObject)Instantiate(panelPrototype, new Vector3(0,0.5f,0), Quaternion.identity);
panel.renderer.material.mainTextureOffset = new Vector2(col/16.0f, (15-row)/16.0f);
...the result appears to be panels that are linked together. Both the original and the clone always have the same look, and even if I change the texture offset in the editor for one, it changes it for the other.
I would speculate that this is because Instantiate did not do a deep copy, but instead gave me a clone that's sharing the same material object as the original. If there's only one material object, then of course all objects using it will look the same. But I thought that JavaScript and C# were calling through to the same stuff under the hood. So why is the behavior different? And, how would I go about cloning an object and giving it a unique look in C#?
Answer by Lemon · Feb 08, 2011 at 10:19 AM
Just had a similar problem. You are correct in assuming that this happens because a deep copy was not performed. You can force the deep copy yourself:
panel.renderer.material = Instantiate (panel.renderer.material) as Material;
note that you may in turn need to copy the texture for the Material as well:
panel.renderer.material.mainTexure = Instantiate (panel.renderer.material.mainTexture) as Texture2D;
Thanks, that's a neat trick and sounds like it'll solve the problem.
I still find it disturbing that the same function behaves differently in JavaScript vs. C#, though!
Answer by $$anonymous$$ · Jun 15, 2015 at 09:46 AM
If anyone has this problem with materials being shared by default, this might help:
void Awake() {
Text t = GetComponentInChildren<Text>();
// Ensure that this material is NOT the shared one!!!
Material m = t.material;
t.material = new Material(m);
}
This helped solve an issue I had where a Canvas Text material was using the shared material, and I wanted it to use its own independent material.
Your answer
Follow this Question
Related Questions
How to assign different TEXTURES to objects with the same mesh? 1 Answer
Dynamic Material & Textures 1 Answer
Adding a Material to Particle System 1 Answer
Texture not showing on game objects 1 Answer
Regular grid on irregular mesh 0 Answers