Search Unity

Question Unity random spawn objects

Discussion in 'C# Job System' started by KateNuz, Dec 23, 2022.

Thread Status:
Not open for further replies.
  1. KateNuz

    KateNuz

    Joined:
    Dec 23, 2022
    Posts:
    2
    Hello!
    I really need help with Unity for my uni project. I have chest collectibles that spawn at random spawn points, the problem is that I need only about 15 of them to spawn, but they spawn infinitely. I don't know how to fix this. Also, maybe somebody knows how to prevent them from overlapping.
    Here's the code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GameController : MonoBehaviour
    6. {
    7.     public int numberRandomPositions = 8;
    8.     public int ChestCount = 0;
    9.     public GameObject chestPrefab;
    10.     public List<Transform> spawnpoints = new List<Transform>();
    11.     float chestTimer = 0f;
    12.     float minX;
    13.     float maxX;
    14.     float minY;
    15.     float maxY;
    16.  
    17.     void Start()
    18.     {
    19.       Vector3 viewportBottomLeft = Camera.main.ViewportToWorldPoint(new Vector3(0f, 0f, 0f));
    20.       Vector3 viewportTopRight = Camera.main.ViewportToWorldPoint(new Vector3(1f, 1f, 0f));
    21.    
    22.  
    23.  
    24.         minX = viewportBottomLeft.x;
    25.         maxX = viewportTopRight.x;
    26.         minY = viewportBottomLeft.y;
    27.         maxY = viewportTopRight.y;
    28.  
    29.     }
    30.        
    31.     // Update is called once per frame
    32.     void Update()
    33.     {
    34.        chestTimer += 1f * Time.deltaTime;
    35.         if (chestTimer >= 5f)
    36.         {
    37.          for (int i = 0; i < 2; i++)
    38.          {
    39.           int spawnIndex = Random.Range(0, spawnpoints.Count -1);
    40.           Instantiate(chestPrefab, spawnpoints[spawnIndex].transform.position, transform.rotation);
    41.          }
    42.             chestTimer = 0f;
    43.         }
    44.  
    45.     }
    46. }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,474
    Do not cross-post threads, especially to forums that don't relate to your post at all.

    Your post has nothing to do with the Job System.
     
Thread Status:
Not open for further replies.