I am procedurally generating a 2D tile map by instantiating GameObjects of varying Sprite prefabs, but I am having difficulty in understanding how to properly set the alpha (opacity) value of an individual Sprite without affecting all Sprites instantiated from the same prefab.
In my BoardManager script, I have something like the following:
GameObject segment;
segment = Instantiate(_segmentPrefabs[_segmentControl[seg]], new Vector3(0, seg), Quaternion.identity) as GameObject;
segment.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, 0.5f);
I would expect this to only affect the GameObject instance I just created and not every GameObject using the same prefab. Additionally, this modifies the prefab’s alpha value in Unity itself, so I have to remember to set it back to the normal value in Unity. This is in no way the behavior I’d expect, coming from other engines (e.g. Phaser/Pixi). Further, it seems more intuitive that I should be able to just modify the alpha channel directly, rather than having to instantiate a new Color object, but this does not seem possible. E.g.
segment.GetComponent<SpriteRenderer>().color.a = 0.5f;
Conversely, I am able to create multiple Sprites in my scene view by dragging the same prefab into the scene and then adjust the alpha values of each individually. This leads me to believe that dragging the prefab objects into the Scene view instantiates the Sprites differently than what I keep reading to do in the script. One other obvious difference I am noticing is that when I create these objects in the script, they are labeled as “copies” when looking at the Hierarchy, whereas the ones I drag into the scene are not labeled as copies.
That said, I’m hoping someone can highlight the differences between adding via the Scene view versus Instantiating in the script, and what I might be doing incorrectly. Thank you!
Edit: To take this a little further, my intention is also to change a Sprite’s texture, when the mouse is over it, and so I imagine I will experience a similar issue when I want to do that.