Vladimiro25

Unity

Feb 25th, 2021
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class RoadSpawner : MonoBehaviour
  6. {
  7.     public GameObject[] RoadBlocksPrefab;
  8.     public GameObject StartBlockPrefab;
  9.  
  10.     float BlockPosX = 0;
  11.     int BlocksCount = 7;
  12.     float BlocksLength = 0;
  13.     int SafeZone = 40;
  14.  
  15.     public Transform PlayerTransform;
  16.     List<GameObject> CurrentBlocks = new List<GameObject>();
  17.     // Start is called before the first frame update
  18.     void Start()
  19.     {
  20.         BlockPosX = StartBlockPrefab.transform.position.z;
  21.         BlocksLength = StartBlockPrefab.GetComponent<BoxCollider>().bounds.size.z;
  22.  
  23.         for (int i = 0; i < BlocksCount; i++)
  24.         {
  25.             SpawnBlock();
  26.         }
  27.     }
  28.  
  29.     // Update is called once per frame
  30.     void Update()
  31.     {
  32.         CheckForSpawn();
  33.     }
  34.  
  35.     void CheckForSpawn()
  36.     {
  37.         if (PlayerTransform.position.z - SafeZone > (BlockPosX - BlocksCount * BlocksLength))
  38.         {
  39.             SpawnBlock();
  40.             DestroyBlock();
  41.         }
  42.     }
  43.  
  44.     void SpawnBlock()
  45.     {
  46.         GameObject block = Instantiate(RoadBlocksPrefab[Random.Range(0, RoadBlocksPrefab.Length)], transform);
  47.  
  48.         BlockPosX += BlocksLength;
  49.  
  50.         block.transform.position = new Vector3(0, 0, BlockPosX);
  51.  
  52.         CurrentBlocks.Add(block);  
  53.     }
  54.     void DestroyBlock()
  55.     {
  56.         Destroy(CurrentBlocks[0]);
  57.         CurrentBlocks.RemoveAt(0);
  58.     }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment