- Home /
How do I make my code so it only spawns one object in the area i chose?
Can someone please help me figure out how to make it so when I click play it only spawns one object because when I click play it spawns a ton of objects that fill up the space. please help. using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SpawnObject : MonoBehaviour {
public Vector3 center;
public Vector3 size;
public GameObject KeyPrefab;
// Use this for initialization
void Start () {
SpawnKey();
}
// Update is called once per frame
void Update () {
}
public void SpawnKey()
{
Vector3 pos = center + new Vector3(Random.Range(-size.x / 2, size.x /2), Random.Range(-size.y / 2, size.y / 2), Random.Range(-size.z / 2, size.z / 2));
Instantiate(KeyPrefab, pos, Quaternion.identity);
}
void OnDrawGizmosSelected()
{
Gizmos.color = new Color(1,0,0,0.5f);
Gizmos.DrawCube(center, size);
}
}
Answer by SullyCreates · Oct 21, 2018 at 07:26 PM
Is the script that you are using connected to your prefab? If so, when a new GameObject is created, it runs your Start() function and creates another clone of itself and continues the infinite chain of creations. I would suggest creating an Empty GameObject with merely that script attached.
Your advice worked but when I expand the area where the object can spawn sometimes it spawns in a tree do you know how to stop this?
This could certainly not be solved with one line of code. The question is answered.
Your answer
![](https://koobas.hobune.stream/wayback/20220612180717im_/https://answers.unity.com/themes/thub/images/avi.jpg)