Setting the parent of an instantiated prefab error

Hello,

Before anything, I have looked around, as this seems to be a common error and quite well documented. I know that the error occurs when trying to modify the transform of a prefab. I do not think I am doing that.

I have the following script attached to a prefab object - it’s a card for a card game. The script is to drag and drop the card.

It works very well as long as the card is instantiated before I play the game ; if I instantiate it in game and try to move it I get the following error :

Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption

public class CardDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    // HANDLES DRAG OF CARDS
   
    private Transform originalParent; // saving the original parent
    private Card card; // Card is a scriptable object, card holds data
    private Transform canvas; // a reference to the main canvas

    public void SetCanvas(Transform setCanvas)
    {
        canvas = setCanvas;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        originalParent = transform.parent;
        transform.SetParent(canvas); // WHERE THE ERROR HAPPENS
    }

    public void OnDrag(PointerEventData eventData)
    {
        gameObject.transform.position = Input.mousePosition;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        gameObject.transform.SetParent(originalParent);
    }
}

The script that handles cards in hand is the following one ; it instantiates the cards that are to be dragged in the game.

public class HandManager : MonoBehaviour
{
    // MANAGES GENERAL BEHAVIOURS FOR THE HAND OF CARDS

    public GameObject cardPrefab; // a prefab reference to a card
    public Transform canvas; // a reference to the main UI canvas
    public Hand availableCards; // another scriptable object, which holds a "public List<Card> cards;"

    private void Start()
    {
        foreach (Card card in availableCards.cards)
        {
            SetUpCard(card);
        }
    }

    private void SetUpCard(Card cardData)
    {
        GameObject newCard= Instantiate(cardPrefab, transform); // instantiating new card
        newCard.GetComponent<CardManager>().SetCardData(cardData); // setting the card's data
        newCard.GetComponent<CardDrag>().SetCanvas(canvas);
    }
}

I have been looking this error up, and it is always said that the problem occurs when attempting to change a prefab’s parent instead of a prefab’s instance’s parents.

I do not see the problem though, since I believe I’m instantiating the cards properly in the SetUpCard() function ; and the script that manages the dragging is attached to that instance.

Any insights greatly appreciated !

Cheers !!

Turns out the error message meant the canvas was the problem.

I had messed up the reference in the editor…