Search code examples
unity-game-engineinstantiationgame-developmentgameobject

Unity how to get component reference on instantiated object


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

How can i get reference to playedCard's SpriteRenderer?


Solution

  • 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);