Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Set parent for instantiated object being a list

Discussion in 'Scripting' started by ellenblomw, Jul 20, 2018.

  1. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    153
    Hi,

    I'm a n00b trying to get my instantiated gameobjects to instantiate as child objects. When I try the solutions I can find by searching none of them works. My instantiated objects are from a list, maybe that is why they don't work.

    This is my working code:

    Code (CSharp):
    1.     public List<GameObject> Char1;
    2.     public List<GameObject> Char2;
    3.     public List<GameObject> Char3;
    4.  
    5.     // Use this for initialization
    6.     void Start()
    7.     {
    8.        Instantiate(Char1[PlayerPrefs.GetInt("Char1Number") - 1]);
    9.        Instantiate(Char2[PlayerPrefs.GetInt("Char2Number") - 1]);
    10.        Instantiate(Char3[PlayerPrefs.GetInt("Char3Number") - 1]);
    11.     }
    I tried transform.setParent like this:
    Code (CSharp):
    1.        Instantiate(Char1[PlayerPrefs.GetInt("Char1Number") - 1], transform.SetParent("cover"));
    I also tried char1.transform.parent... after object is instantiated, but it didn't work either. It gave me the following error: "Assets/scripts/loadCharacters.cs(17,16): error CS1061: Type `System.Collections.Generic.List<UnityEngine.GameObject>' does not contain a definition for `transform' and no extension method `transform' of type `System.Collections.Generic.List<UnityEngine.GameObject>' could be found. Are you missing an assembly reference?"

    What am I doing wrong?

    Respectfully,
    Ellen
     
    Last edited: Jul 20, 2018
  2. Leonetienne500

    Leonetienne500

    Joined:
    Dec 5, 2016
    Posts:
    130
    Hey, i'd like to advise you to use the full Instanciate function.
    If you want to instanciate a gameobject at the position / rotation set in the prefab as a child of the gameobject named "Cover" use this:


    GameObject charPrefab = Char1[PlayerPrefs.GetInt("Char1Number") - 1];
    GameObject charHandle = Instanciate(charPrefab, Vector3.zero, Quaternion.Euler(Vector3.zero), GameObject.Find("Cover").transform);

    charHandle.transform.position = charPrefab.transform.position;
    charHandle.transform.rotation = charPrefab.transform.rotation;
    //The Instanciate function sometimes F***s up the position / rotation so just set it again


    there could be typos in the code. I have just written it here, not in an ide.
    Hope it helps!
     
  3. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    153
    Thank you so very very much! This has been bugging my brain the whole day. Your solution worked like a charm!
     
    Leonetienne500 likes this.