Home > Enterprise >  Unity how to get component reference on instantiated object
Unity how to get component reference on instantiated object

Time:07-15

var playedCard = Instantiate(Cards[selectedCard], spawnLoc[gameQueue - 1], Quaternion.identity);

How can i get reference to playedCard's SpriteRenderer?

CodePudding user response:

Considering Cards[selectedCard] holds a reference to a GameObject, you can go with

var sp = playedCard.GetComponent<SpriteRenderer>();

Or if Cards is an array of SpriteRenderer itself, Instantiate should return a new GameObject via its spriteRenderer Reference (you may need to add an explicit cast before Instantiate in this case, as such

var sp = (SpriteRenderer)Instantiate(Cards[selectedCard], spawnLoc[gameQueue - 1], Quaternion.identity);
  • Related