Hello, I am working on a small 2D game called “Protect the Square”, whereas the name suggests the player must protect a square from circular enemy’s via powerups, controlling the square itself, and controlling a paddle used to deflect the enemies. I am currently working on an endless mode, where the level is continuously generated from handmade prefabs as the player progresses though it, but I am running into an issue. After 4 to 5 segments(prefabs) are instantiated successfully, future segments, while still being instantiated, are invisible in the game view. As this feature is still a work in progress, I only have two prefabs made at the moment, and at the beginning of the level, both prefabs instantiate correctly, but after the 4 to 5 segment threshold is reached, the same prefabs which were previously instantiating correctly become invisible. Once this happens to one prefab it happens to all future prefabs, but collisions still work as expected. Despite being invisible in game view, the prefabs appear normal in the editor. I have tried saving my game and restarting Unity, but other than that, I’m clueless on what is causing this or how to troubleshoot and fix it. I have included my level generation script below, although I doubt that the script is the problem because even the problematic prefabs are instantiated in the correct positions. Any help or insight would be greatly appreciated.
Thanks,
CT
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelSpawner : MonoBehaviour
{
public GameObject[] levelPrefabs; // Array of level prefabs
public Transform square; // Reference to the square object
public float triggerDistance; // Distance at which to trigger the next level piece
public Transform startingSpawnPoint; // Spawn point of the starting piece
private Transform lastSpawnPoint; // Last spawn point
void Start()
{
lastSpawnPoint = startingSpawnPoint;
}
void Update()
{
// Check if the square is close enough to the last spawn point to trigger the next level piece
if (Vector2.Distance(square.position, lastSpawnPoint.position) <= triggerDistance)
{
// Select a random level prefab
int index = Random.Range(0, levelPrefabs.Length);
GameObject levelPrefab = levelPrefabs[index];
// Determine the position for instantiating the new level piece
Vector3 spawnPosition = lastSpawnPoint.position;
// Instantiate the level prefab at the spawn position
GameObject newLevelPiece = Instantiate(levelPrefab, spawnPosition, Quaternion.identity);
// Update the last spawn point
lastSpawnPoint = newLevelPiece.transform.Find("SpawnPoint");
}
}
}