Search Unity

Tiles spawn on top of eachother

Discussion in 'Scripting' started by idrix, Jun 1, 2019.

  1. idrix

    idrix

    Joined:
    May 28, 2019
    Posts:
    1
    Hi,

    I've been trying to create a endless runner type of game as my first project.

    Right now my script generates a path using tiles, it adds tiles and removes them from the back. Id like to make the tiles random, so that I can add different obstacles to them. I created two prefab tiles but they seem to spawn on top of eachother and I don't know what's wrong with the script.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class TileManager : MonoBehaviour {
    6.  
    7. public GameObject[] tilePrefabs;
    8.  
    9. private Transform playerTransform;
    10. private float spawnZ = -5.6f;
    11. private float tileLength = 5.0f;
    12. private float safeZone = 30.0f;
    13. private int amnTilesOnScreen = 7;
    14. private int lastPrefabIndex = 0;
    15.  
    16. private List<GameObject> activeTiles;
    17.  
    18.  
    19. // Use this for initialization
    20. private void Start () {
    21.  
    22.   activeTiles = new List<GameObject>();
    23.   playerTransform = GameObject.FindGameObjectWithTag ("Player").transform ;
    24.  
    25.   for (int i = 0; i < amnTilesOnScreen; i++) {
    26.  
    27.    if (i < 2) {
    28.     SpawnTile (0);
    29.    } else {
    30.     SpawnTile ();
    31.    }
    32.  
    33.   }
    34. }
    35. // Update is called once per frame
    36. private void Update () {
    37.  
    38.   if (playerTransform.position.z - safeZone > (spawnZ - amnTilesOnScreen * tileLength)) {
    39.  
    40.    SpawnTile ();
    41.    DeleteTile ();
    42.   }
    43. }
    44.  
    45. private void SpawnTile(int prefabIndex = -1){
    46.  
    47.   GameObject go;
    48.   if (prefabIndex == -1) {
    49.    go = Instantiate (tilePrefabs [RandomPrefabIndex ()]) as GameObject;
    50.   } else {
    51.    go = Instantiate (tilePrefabs [prefabIndex]) as GameObject;
    52.   }
    53.  
    54.   go.transform.SetParent (transform);
    55.   go.transform.position = Vector3.forward * spawnZ;
    56.   spawnZ += tileLength;
    57.   activeTiles.Add (go);
    58. }
    59.  
    60. private void DeleteTile (){
    61.   Destroy (activeTiles [0]);
    62.   activeTiles.RemoveAt (0);
    63. }
    64.  
    65. private int RandomPrefabIndex() {
    66.  
    67.   if (tilePrefabs.Length <= 1) {
    68.  
    69.    return 0;
    70.   }
    71.  
    72.  
    73.  
    74.   int randomIndex = lastPrefabIndex;
    75.   while (randomIndex == lastPrefabIndex) {
    76.    randomIndex = Random.Range (0, tilePrefabs.Length);
    77.   }
    78.  
    79.   lastPrefabIndex = randomIndex;
    80.   return randomIndex;
    81. }
    82. }
    https://imgur.com/a/bxtYpKL