- Home /
C# attach GO to script's parent
Hello!
I've the follwing Setup:
A GO somewhere in my worldspace. A script attach to that. In that script a new GO(myNewCube) spawns and i want it to be a parent of the first GO (with script attached).
How can i do this?
myNewCube.transform.parent = transform.parent.gameObject.transform;
Don't work.
Problem is, it must be dynamic and i can't search for the scripts name because i would get back alot of them.
Answer by GameVortex · Nov 13, 2014 at 02:05 PM
If the myNewCube is created in the parent GO (the one with the script). Then simply set the parent to be the transform of the script/component.
myNewCube.transform.parent = transform;
Thats to easy..
.. but i works! Thanks for that. :D
But now i have another Problem. The Parent is a Prefab. Didn't thought about that. (Adding a Go to Prefab on runtime is disabled.) But up one level in the hierachy there is a normal GO. How can i access this one in that case?
I am not sure I completely understand your setup. Is the component which spawns the objects not on a GameObject itself in the scene? Could you please detail your hierarchy of objects.
Answer by skaddi · Nov 13, 2014 at 07:24 PM
Ok, i told you something wrong. The script is not attached to a GO but a prefab. And it spawns a prefab. :/
Sure, it looks like this:
GO
GO
GO
GO
PreFab
Script
By now, the script tries to add the new prefab to the upper prefab, which has the script attached. Either i can add the new prefab to the upper GO, or i create a totaly new GO to get all these prefabs spawned by the script. I can write the second solution, but the first solution would be the cleaner one..
Ah, Ok. Problem solved.
(Instantiate(myCube, myVector3, myQuaternion) as GameObject).transform.parent = transform;
But, Thank you! :)