- Home /
How to create multiple gameObjects by code?
I created a little sprite in the editor called lightpink and assigned it to a little script that runs movements. How do I proceed to create more of that object in a control script?
public class SpawnObjects : MonoBehaviour {
private List<GameObject> pinks;
// Use this for initialization
void Start () {
pinks = new List<GameObject>();
}
// Update is called once per frame
void Update () {
CreateNewPinks();
}
private void CreateNewPinks()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//Magic
}
}
}
Answer by Cherno · Jul 12, 2016 at 03:51 PM
You keep a reference to a Prefab GameObject and instantiate a copy of it.
public class SpawnObjects : MonoBehaviour {
public GameObject pinkPrefab;
private List<GameObject> pinks;
// Use this for initialization
void Start () {
pinks = new List<GameObject>();
}
// Update is called once per frame
void Update () {
CreateNewPinks();
}
private void CreateNewPinks()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GameObject newPink = Instantiate(pinkPrefab, Vector3.zero, Quaternion.identity) as GameObject;
pinks.Add(newPink);
}
}
}
How is the object created in the editor linked with the code? How does pinkPrefab connect with that?
When you instantiate a new GameObject (in this case the "pinkPrefab") you will see it within your editor, in the hierarchy as "pinkPrefab(Clone)".
You also will have a reference to these clones within the 'pinks' list since you add them to said list on instantiation like they did on line 19.
Your answer
![](https://koobas.hobune.stream/wayback/20220612084659im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Adding Text to Canvas via script 4 Answers
Position Text inside Canvas via Script 2 Answers
TextMeshPro Array 1 Answer
How to use GameObject like Button? 1 Answer
Fundamental question about Update() 1 Answer