Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question So many GameObjects are instantiated Problem

Discussion in 'Scripting' started by mr_bhujel, Oct 7, 2023.

  1. mr_bhujel

    mr_bhujel

    Joined:
    Oct 5, 2023
    Posts:
    3
    I am trying to spawn objects ramdomly but when I run the code the objects and so many objects are instantiated. I added 3 elements in the GameObject array and each time 'S' is pressed many number of objects are created. I don't know how to solve the problem and I don't know where I made mistake. Even if I provide a single index value, I get the same problem. Please someone help me on this.

    Here is the code that I used, I don't know where I made mistake. I took 3 prefabs and added to the arary but instead of one, many objects are created.


    Code (CSharp):
    1. public class SpawnManager : MonoBehaviour
    2. {
    3.     public GameObject[] animalPrefabs;
    4.     public int spawnPosZ = 20;
    5.     public int spawnRangeX = 20;
    6.    
    7.     void Start()
    8.     {
    9.        
    10.     }
    11.  
    12.     void Update()
    13.     {
    14.         if (Input.GetKey(KeyCode.S))
    15.         {
    16.             int animalIndex = Random.Range(0, animalPrefabs.Length);
    17.             Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, spawnPosZ);
    18.             Instantiate(animalPrefabs[animalIndex], spawnPos, animalPrefabs[animalIndex].transform.rotation);        
    19.         }
    20.     }
    21. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    Theleoboy likes this.
  3. mr_bhujel

    mr_bhujel

    Joined:
    Oct 5, 2023
    Posts:
    3