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;
    }
}

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.

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