Hi,
I currently have an empty GameObject “World” that has a JS script that codes for the instantiation of prefabs “Tube” every time a different GameObject “Arrow” is clicked. My prefab Tubes contain a script that uses SendMessageUpwards to communicate with World’s script which will then perform another action. Every Tube needs to communicate with World and vice versa. However, the prefabs get instantiated outside of the World object so they can’t communicate. BroadcastMessage doesn’t work either.
Is there a way to instantiate within another object? Would it be easier to use a GetComponent method?.. I’m not sure about this since there will be several Tubes.
Any thoughts are appreciated.
Yes, you can set the transform’s parent to the GameObject you want it to be a child of.
GameObject object = (GameObject)Instantiate(prefab, Vector3.zero, Quaternion.identity);
object.transform.parent = parentObject;
Thanks for your quick reply!
I’m glad this can be done, but I’m having some problems with the code… the log always says I’m missing a “;” even though its clearly there. Was that written in C#? My file is in JS so maybe that’s the problem…
Yes, that was written in C#.
The only difference in that code is:
GameObject object =
//becomes
var object : GameObject =
Yes, this was C#. Here is JS for you (I think this is correct).
var newObject = Instantiate(prefab, Vector3.zero, Quaternion.identity);
newObject.transform.parent = parentObject;
Thanks again, though still having issues…
This is what I have right now:
var parentObj : GameObject; //here I drag the "World" empty GO
var prefab : GameObject; //here I drag my prefab from my project folder
private var newObject : GameObject = Instantiate(prefab, Vector3.zero, Quaternion.identity);
newObject.transform.parent = parentObject;
With this I get “Cannot convert ‘UnityEngine.GameObject’ to ‘UnityEngine.Transform’” and also that the prefab I want to instantiate is null… however, it was not null when I was instantiating like this:
parentObject.Instantiate(tubesInst, Vector3.zero, Quaternion.identity);
… but that doesn’t put it in the parentObject either, though it’s successfully instantiated…
parentObject needs to be a Transform.
Yeah, what Dman said. Just change the last line to:
newObject.transform.parent = parentObject.transform;
No problem. Glad we could help.