- Home /
Can't add sprite to instantiated GameObject
I'm trying to add a sprite to an instantiated gameObject, but when the object is created, the sprite is not added. Here's the code:
public class CardLieDetector : MonoBehaviour
{
#region variables
public SelectingCard cardScript; //Script where the sprite is located
#endregion
// Start is called before the first frame update
void Start()
{
ShowCarta();
}
// Update is called once per frame
void Update()
{
}
public void ShowCarta()
{
GameObject carta = new GameObject(); //GameObject I want to add the sprite to
carta.AddComponent<SpriteRenderer>();
carta.GetComponent<SpriteRenderer>().sprite = cardScript.cardSelected;
}
}
Answer by Naggil · Jan 08, 2020 at 04:08 AM
It's supposed to be working, try using another way to reference the sprite like a public Sprite variable on the same script and Im sure that it will work, the problem here is clearly the cardScript.cardSelected if its reference is set inside the start function the problem can be solved if u change it to awake function instead, if it's not the case u can send ur cardScript code or trying fix it ur self but Im pretty sure that the problem is there
I solved the problem. I just instantiated a new GameObject prefab with the Sprite ins$$anonymous$$d of calling SelectingCard variables.
Answer by LOSTSOUL86 · Jan 06, 2020 at 04:45 AM
Hi,
the code looks ok. What I would change is to put declaration of the carta GameObject outside of ShowCarta method. where you declare cardScript declare carta;
Let me know if that works.
Hi, I did what you told me but the same keeps happening. I thought it happens because there may be no sprite assigned to cardScript.cardSelected, but I just checked it and there is.