- Home /
How to make an Instantiated prefab a Child of a gameobject that already exists in the hierarchy
Hi I have a script which will Instantiate prefabs which works fine but I wanted them to be added to a gameobject that already exists and make the instantiated prefab a child of the already existing gameobject without making a new one. If it helps here is the script...
if (randomizer == 1 && i <= 0)
{
Instantiate(A, new Vector3 (0,0,0), Quaternion.identity);
System.Random random = new System.Random();
randomizer = random.Next (1,5);
i++;
}
and an image of what gameobject I want the Instantiated objects to become children of. Thank you in advance and thank you for helping me with my studies.
$$anonymous$$ebabs is right! +1 It's a easy question. If you check API. You will get more
Hi. If you found the correct answer, please mark you question as Closed(from the edit button). Thank you.
Answer by robertbu · Dec 01, 2013 at 01:34 AM
If I understand your question correctly, you can replace line 3 with these two lines:
GameObject go = Instantiate(A, new Vector3 (0,0,0), Quaternion.identity) as GameObject;
go.transform.parent = GameObject.Find("Stage Scroll").transform;
Can someone explain me, Instantiate function creates a "Object" variable Object class is parent to GameObject. So why are we able to cast Object as GameObject. I thought you can't cast children class with "as" it will return null if done so. So can somebody answer me why is it possible ? ;s
@Tunexxx The 'as' cast will only give you null if the thing you're casting cannot be cast to the class you're trying to cast it to. It can be used to check whether or not an object is of a particular (derived) type.
In most cases, when using Instantiate one knows what it is that one is instantiating, so this "null check" can safely be left out. But if you're not sure then yes, you should check for null immediately after casting, before trying to use the variable.
Answer by d2clon · Feb 10, 2021 at 08:25 PM
Instantiate has several acceptations and a couple of them already accept the Transform element which will become the parent of the instantiate object, check the documentation:
Answer by luthoff44 · Sep 04, 2021 at 08:03 PM
it has random position when instatianted lik -5.51 1.26 -35.37 how do i make it 0,0,0?
Your answer
Follow this Question
Related Questions
Parenting an instantiated prefab. 1 Answer
Spawn Prefabs 1 Answer
Photon Instantiate Prefab Script Problems 0 Answers
Retrieving GameObjects from a Prefab 1 Answer