While doing the challenge to set the smoke’s color to that of the broken block, I initially tried to find the
SpriteRenderer member of
this.gameObject (inside the brick script). When this didn’t work, I did a little doc digging and came up with a different way of accessing the brick’s color than what Ben uses. The
brick object doesn’t register as having a
SpriteRenderer component because we are typing it as a
GameObject in the script instead of a
Sprite, but it does have a
renderer component. It appears that
renderer actually is a
SpriteRenderer (Unity just doesn’t expect to see a
SpriteRenderer on something it is just treating as a
GameObject), so we can cast it to the proper class and access the color as desired.
GameObject smokePuff = (Instantiate(smoke, this.transform.position, Quaternion.identity) as GameObject); smokePuff.particleSystem.startColor = (this.gameObject.renderer as SpriteRenderer).color;
Is there any reason not to use this technique? I would expect it to be slightly quicker than calling a method to search for the relevant component, if only by a hair.
While I’m asking, does the C# compiler compress the above to be the same machine commands as doing it all in one line, as below, or would writing it as below be better in cases where getting optimal speed is necessary/desired? I know some compilers for languages like C++ make optimizations like that (in this case because the variable is only ever used right there), but C# is completely new to me.
(Instantiate(smoke, this.transform.position, Quaternion.identity) as GameObject).particleSystem.startColor = (this.gameObject.renderer as SpriteRenderer).color;