x


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#?

more ▼

asked Feb 01 '11 at 06:57 PM

JoeStrout gravatar image

JoeStrout
177 8 8 16

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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;
more ▼

answered Feb 08 '11 at 10:19 AM

Lemon gravatar image

Lemon
194 5 5 13

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!

Feb 09 '11 at 03:13 PM JoeStrout
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2190
x1669
x807
x130

asked: Feb 01 '11 at 06:57 PM

Seen: 2199 times

Last Updated: Feb 01 '11 at 06:57 PM