- Home /
Instantiating as a child error
void BubbleCome() {
Instantiate(bubble, new Vector3(transform.position.x + 1f, transform.position.y + 1.5f, transform.position.z + 1), Quaternion.Euler(new Vector3(38, 0, 0)));
bubble.transform.parent = transform;
Invoke("BubbleCome", Random.Range(repeatMin, repeatMax));
}
The idea is that the continuously instantiated object (bubble) becomes a child of the game object to which the script is attached to pretty much as soon as it spawns. But the problem is that unity gives me an error:
"Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption."
Any idea why this happens and how I could fix it? Other than this function the only other one is the "BubbleCome();" set in the Start function.
Thanks! :)
Answer by nicolasjr · Apr 12, 2014 at 06:43 PM
I think you should create a GameObject pointer to instantiate it. such as:
GameObject newBubble = (GameObject)GameObject.Instantiate(bubble, new Vector3(transform.position.x + 1f, transform.position.y + 1.5f, transform.position.z + 1), Quaternion.Euler(new Vector3(38, 0, 0)));
Then:
newBubble.transform.parent = transform;
It works! Thank you so much! :)
If you don't $$anonymous$$d telling me why it should be like that? I mean, I understand that pointers point at a certain part of the memory, but simply why do we have to use them ins$$anonymous$$d of simply using the object (prefab) we just dragged into our script.
Of course, it's not obligated, it's just so I know what to do and why I'm doing something next time I try to do something similar (I hope that makes sense).
Again, thanks! :)
Hey $$anonymous$$itty,
That happens because your prefab is not in the hierarchy, so, you're trying to change it's parent when, in truth, it doesn't have any. Does that makes sense?
You can only access parents of transforms in the scene, and, despite the fact that you instantiated a prefab in the scene, you still trying to change properties from the pointer you have from the prefab outside the scene!
Hope I could explain well enough!
Ah, so I'm trying to manipulate the prefab it self, but not the object inside the hierarchy. I didn't understand it at first, but I think I know what you mean! Thanks again, Nicolas!
Exactly, $$anonymous$$itty! you got it right! Good thing I was able to explain it properly. :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613142547im_/https://answers.unity.com/themes/thub/images/avi.jpg)