Parenting a GameObject in a list

Hi folks,

I am creating a list of GameObjects and trying to parent each object with the following code:

       GameObject.Find("Panel").GetComponent<Image>().sprite = loadedImage;
        circlePrefab = (GameObject)Resources.Load("TargetCircle");
        targetCircle.Add(circlePrefab);
        targetCircle[0].transform.SetParent(uiPanel.transform, false);
        xPos = (int)targetCircle[0].transform.position.x;

I get an error “Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption.”

Before I changed from an array to a list, which is necessary, the following code worked:

  targetCircle[x] = Instantiate(circlePrefab);
  targetCircle[x].transform.SetParent(uiPanel.transform, false);

I assume therefore the absence of an Instantiate for the list item is a problem. Am I right and if so how do I do this and if I am wrong, how do I do this?

Thanks in advance,

You are (probably ) right, and how to do this i, Instantiate first your prefab then attach everything you want to it

1 Like

Thanks for the answer. I tried this, which is what I think you were suggesting:

      circlePrefab = (GameObject)Resources.Load("TargetCircle");
        circleInstantiate = Instantiate(circlePrefab);
        circleInstantiate.transform.SetParent(uiPanel.transform,false);
        targetCircle.Add(circlePrefab);
        // targetCircle[0].transform.SetParent(uiPanel.transform, false); //added this after GameObject did not appear. Same parenting error as in original post

No error, but also the GameObject does not appear in the scene. Tried adding the second Setparent just in case, but get the original error.

Just an update. The GO does appear in the scene, but way off screen. PosX is over 4000. Again I assume fixing the parenting error will resolve this.

When it’s in the scene, is it parented properly?

Generally when I change the parent of something that is instantiated, I may sometimes have to change it’s localposition after, depending on the situation.

But setParent also includes a bool parameter to keep world position, which may be all you need. It just depends on the situation.

You can also declare position with Instantiate for the object you are spawning. Note that Instantiate also lets you declare a parent object as a parameter if you want to do that instead of creating and then setting the parent.

1 Like

I found my error in what I tried after the first suggestion. I wrote:

irclePrefab = (GameObject)Resources.Load("TargetCircle");
        circleInstantiate = Instantiate(circlePrefab);
        circleInstantiate.transform.SetParent(uiPanel.transform,false);
//        targetCircle.Add(circlePrefab); This was the error
       targetCircle.add(circleInstantiate); // This is what it should have been

That removes the parenting error and now I can just do the reposition.

Thanks to all for your input.

Cool, glad you got it working.