Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Cannot change parent of object after instantiation

Discussion in 'Scripting' started by Darknessaint, Feb 19, 2023.

  1. Darknessaint

    Darknessaint

    Joined:
    Jan 18, 2023
    Posts:
    1
    Hey all,

    I'm trying to change the parent of an object after instantiation but keep getting an error saying i'm unable to set the parent
    upload_2023-2-19_12-16-8.png

    Code (CSharp):
    1.  public GameObject panel;
    2.     public HandCard cardPrefab;
    3.    
    4.     public void AddCard(int index)
    5.     {
    6.         GameObject cardObj = Instantiate(cardPrefab.gameObject);
    7.         cardObj.transform.SetParent(panel.transform);
    8.  
    9.     }
    As a result I can see the new card has been created in the hierarchy view but it's not been assigned a parent and can't be seen in the game view.

    upload_2023-2-19_12-20-31.png

    Thanks in advance
     
  2. Jakub34

    Jakub34

    Joined:
    Jan 20, 2020
    Posts:
    7
    My guess is that you are trying to set the object to the parent of something that exists in the prefab menu. I assume you are trying to set it to either HandPanel or PlayerContent, so try dragging one of those from the hierarchy to your script.
     
  3. Leuki

    Leuki

    Joined:
    Feb 27, 2014
    Posts:
    130
    Code (CSharp):
    1. public GameObject panel;
    2. public HandCard cardPrefab;
    3.  
    4. public void AddCard(int index)
    5. {
    6.     GameObject cardObj = Instantiate(cardPrefab.gameObject, panel.transform);
    7. }
    8.