Search Unity

Prevent spawn object at the same position from a list.

Discussion in '2D' started by loley00, Apr 2, 2021.

  1. loley00

    loley00

    Joined:
    Mar 7, 2021
    Posts:
    1
    Hello everyone, i am brand new to both unity and coding, I am trying to prevent my spwaner to spawn objects from my list at the same position in a row but i couldnt do it. I also made a search on the forum and saw some other topics on this problem but couldnt apply those solutions into my code.


    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using TMPro;
    5. using UnityEngine;
    6. using UnityEngine.SceneManagement;
    7. using UnityEngine.UI;
    8.  
    9. public class GameManager : MonoBehaviour
    10.  
    11. //spawnera alternatif daha güzel
    12. {
    13.     public List<GameObject> targets;
    14.  
    15.     // Start is called before the first frame update
    16.     private int score;
    17.     private int i = -1;
    18.     public TextMeshProUGUI scoreText;
    19.     public TextMeshProUGUI gameOverText;
    20.     public Button restartButton;
    21.     public bool isGameActive;
    22.     public float spawnRate = 3.0f;
    23.     public float scoreRate = 4.0f;
    24.  
    25.  
    26.  
    27.     void Start()
    28.     {
    29.         isGameActive = true;
    30.         score = 0;
    31.         UpdateScore(0);
    32.         StartCoroutine(SpawnTarget());
    33.      
    34.        
    35.  
    36.     }
    37.     IEnumerator  SpawnTarget()
    38.     {
    39.         while (isGameActive)
    40.         {
    41.             yield return new WaitForSeconds(spawnRate);
    42.             int index = Random.Range(0, targets.Count);
    43.             Instantiate(targets[index]);
    44.  
    45.          
    46.                 UpdateScore(5);
    47.            
    48.          
    49.         }
    50.     }
    51.     // Update is called once per frame
    52.     public void UpdateScore(int scoreToAdd)
    53.     {
    54.  
    55.         score += scoreToAdd;
    56.         scoreText.text = "Score: " + score;
    57.  
    58.     }
    59.  
    60.     public void GameOver()
    61.     {
    62.         restartButton.gameObject.SetActive(true);
    63.         gameOverText.gameObject.SetActive(true);
    64.         isGameActive = false;
    65.         Time.timeScale = 0;
    66.  
    67.  
    68.     }
    69.     public void RestartGame()
    70.     {
    71.         SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    72.         Time.timeScale = 1;
    73.        
    74.        
    75.     }
    76.    
    77.   }
    78.  
    79.  
    80.  
    81.