Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class RoadSpawner : MonoBehaviour
- {
- public GameObject[] RoadBlocksPrefab;
- public GameObject StartBlockPrefab;
- float BlockPosX = 0;
- int BlocksCount = 7;
- float BlocksLength = 0;
- int SafeZone = 40;
- public Transform PlayerTransform;
- List<GameObject> CurrentBlocks = new List<GameObject>();
- // Start is called before the first frame update
- void Start()
- {
- BlockPosX = StartBlockPrefab.transform.position.z;
- BlocksLength = StartBlockPrefab.GetComponent<BoxCollider>().bounds.size.z;
- for (int i = 0; i < BlocksCount; i++)
- {
- SpawnBlock();
- }
- }
- // Update is called once per frame
- void Update()
- {
- CheckForSpawn();
- }
- void CheckForSpawn()
- {
- if (PlayerTransform.position.z - SafeZone > (BlockPosX - BlocksCount * BlocksLength))
- {
- SpawnBlock();
- DestroyBlock();
- }
- }
- void SpawnBlock()
- {
- GameObject block = Instantiate(RoadBlocksPrefab[Random.Range(0, RoadBlocksPrefab.Length)], transform);
- BlockPosX += BlocksLength;
- block.transform.position = new Vector3(0, 0, BlockPosX);
- CurrentBlocks.Add(block);
- }
- void DestroyBlock()
- {
- Destroy(CurrentBlocks[0]);
- CurrentBlocks.RemoveAt(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment