x


Setting color on prefab with shader not working?

I have this prefab which contains a Plane mesh, which uses the Transparent/Diffuse shader. The texture is a gray PNG with alpha, and I want to use the shader's MainColor to colorize that PNG. In Editor, this is all well and good.

I have several instances of this prefab, and I need to change the colors of the various instances dynamically. So I get the prefab instances by name and set the color Code:

p = gameObject.Find("Plane"); 
if (!p) 
   Debug.LogError("spot plane not found"); 
p.renderer.material.SetColor ("_Color", scolor); 

The odd thing is, it sets ONE of the instances, not all of them, and it's not always the same instance. I can replace 'scolor' with, say, Color.red, and then one of the instance will colorize. All others stay at the default color.

I would have thought that if it was altering the shader at a 'material' level, then all instances would have the new color.

What's the trick to this?

Should say: 2.6.1 Windows, decent machine

more ▼

asked Jun 10, 2010 at 11:32 PM

DaveA gravatar image

DaveA
33.5k 419 341 467

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

2 answers: sort voted first

GameObject.Find finds one single object. If you have more than one with the same name, which one it finds first has no guaranteed order. If you change renderer.material on an object, Unity creates a new unique scene material for you which is then used for that object. To change the material for all objects using that material, use renderer.sharedMaterial.

more ▼

answered Jun 10, 2010 at 11:43 PM

Eric5h5 gravatar image

Eric5h5
110k 55 185 669

I thought gameObject.Find() (note the lowercase g) would search within that gameObject. Is there a way to find game objects in children (without writing my own iterator, and still, where is the 'getChild' method?)

Jun 11, 2010 at 01:03 AM DaveA

Well I don't know about finding objects like that, but I replaced p = gameObject.Find("Plane"); with p = gameObject.Find(gameObject.name+"/Plane"); and now it works. Thanks for the tip.

Jun 11, 2010 at 01:13 AM DaveA
(comments are locked)
10|3000 characters needed characters left

You can use renderer.sharedMaterial instead of renderer.material if you want to manipulate them all at the same time

more ▼

answered Jun 25, 2010 at 01:33 AM

Mike 3 gravatar image

Mike 3
33k 21 83 292

(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:

x9215
x3080
x2104
x905

asked: Jun 10, 2010 at 11:32 PM

Seen: 3233 times

Last Updated: Jun 10, 2010 at 11:32 PM