Heya,
im trying to spawn some chunks and followed a tutorial that seems to work on the Z axis. the script spawns the ‘chunks’ along the Z axis in front of the player and deletes old ones behind. what im having trouble doing now is getting it to work in all directions.
any help would be great!
i have tried just copying the functions and replacing it for the X, and Y axis, which does work, however the spaces diagonal dont work. as below:
any help would be great ![]()
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChunkManager : MonoBehaviour
{
public GameObject chunkPrefab;
public Transform playerTransform;
private float spawnZ = 0f;
private float spawnX = 0f;
private float spawnY = 0f;
private float chunkLength = 100f;
private int chunkCount = 3;
private float safeZonePlus = 80f;
private List<GameObject> activeChunkZ;
private List<GameObject> activeChunkX;
private List<GameObject> activeChunkY;
// Start is called before the first frame update
void Start()
{
activeChunkZ = new List<GameObject>();
activeChunkX = new List<GameObject>();
activeChunkY = new List<GameObject>();
for(int i = 0; i < chunkCount; i++)
{
SpawnChunkZ();
SpawnChunkX();
SpawnChunkY();
}
}
// Update is called once per frame
void Update()
{
if(playerTransform.position.z - safeZonePlus > (spawnZ - chunkCount * chunkLength))
{
SpawnChunkZ();
DeleteChunkZ();
}
if(playerTransform.position.x - safeZonePlus > (spawnX - chunkCount * chunkLength))
{
SpawnChunkX();
DeleteChunkX();
}
if(playerTransform.position.y - safeZonePlus > (spawnY - chunkCount * chunkLength))
{
SpawnChunkY();
DeleteChunkY();
}
}
private void SpawnChunkZ()
{
GameObject go;
go = Instantiate(chunkPrefab) as GameObject;
go.transform.SetParent(transform);
go.transform.position = Vector3.forward * spawnZ;
spawnZ += chunkLength;
activeChunkZ.Add(go);
}
private void SpawnChunkX()
{
GameObject go;
go = Instantiate(chunkPrefab) as GameObject;
go.transform.SetParent(transform);
go.transform.position = Vector3.right * spawnX;
spawnX += chunkLength;
activeChunkX.Add(go);
}
private void SpawnChunkY()
{
GameObject go;
go = Instantiate(chunkPrefab) as GameObject;
go.transform.SetParent(transform);
go.transform.position = Vector3.up * spawnY;
spawnY += chunkLength;
activeChunkY.Add(go);
}
private void DeleteChunkZ()
{
Destroy(activeChunkZ[0]);
activeChunkZ.RemoveAt(0);
}
private void DeleteChunkX()
{
Destroy(activeChunkX[0]);
activeChunkX.RemoveAt(0);
}
private void DeleteChunkY()
{
Destroy(activeChunkY[0]);
activeChunkY.RemoveAt(0);
}
}
