- Home /
Question by
colourcrisis · Dec 23, 2018 at 10:31 PM ·
c#gameobjectinstantiateloop
instantiate prefab as child of gameobject with tag
I want to instantiate a prefab as a child for all gameobjects with a certain tag.
I tried this, but it isn't working...
GameObject[] gameObjs;
public GameObject prefab;
GameObject clone;
private void Start()
{
symbols = GameObject.FindGameObjectsWithTag("symbol");
foreach (GameObject go in gameObjs)
{
clone = Instantiate(prefab, go.transform.position, Quaternion.identity) as GameObject;
clone.transform.parent = go.transform;
clone.transform.Translate(0, -150, 0, Space.World);
}
}
Comment
Best Answer
Answer by colourcrisis · Dec 23, 2018 at 11:09 PM
using UnityEngine;
public class Instantiate : MonoBehaviour
{
[SerializedField]
private GameObject prefab;
private GameObject[] objArray;
private GameObject objClone;
private void Start()
{
objArray = GameObject.FindGameObjectsWithTag("tag");
foreach (GameObject item in objArray)
{
objClone = Instantiate(prefab, item.transform.position, Quaternion.identity) as GameObject;
objClone.transform.parent = item.transform;
objClone.transform.Translate(0, 0, 0, Space.World);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612184500im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to not instantiate an object if there is another object there? 1 Answer
Instantiated Prefab doesn't find main camera 2 Answers
Piece of code creates unwanted GameObjects in scene 3 Answers
C# Why do I have to use .AddComponent and not "new (ClassName)"? 1 Answer
How can I check if an instantiated object collides with another instantiated object? 1 Answer