Hopefully I am missing something obvious here, but I have looked up other topics with the same issue and followed the steps and its not working for me.
I am making an endless running type game where objects spawn infinitely as the player progresses and I am trying to destroy the objects when they leave the camera so it doesn’t build up unnecessary objects. I am using OnBecameInvisible to do so however the objects won’t be deleted after becoming invisible in the game view. I have removed the scene view because I know that causes issues with it as well as making sure that my prefabs have a mesh renderer so OnBecameInvisible will work. In game view the camera follows the player. The objects only delete if I have screen view on and scroll with it manually.
One other thing, I am using the cinemachine camera. I don’t know if this is causing issues with it or not but as far as I know the main camera follows the cinemachine camera when its locked on the player so it shouldn’t be but again I’m not sure.
In the code on with Destroy(), I have used gameObject and levelPart1 as well as trying to do an entirely separate script attached to the prefab. Any ideas?
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelSpawn : MonoBehaviour
{
private const float PLAYER_DISTANCE_SPAWN_LEVEL_PART = 200f;
[SerializeField] private Transform levelPartStart;
[SerializeField] private Transform levelPart1;
[SerializeField] private Transform player;
private Vector3 lastEndPosition;
private void Awake()
{
lastEndPosition = levelPartStart.Find("EndPosition").position;
SpawnLevelPart();
int startingLevelParts = 5;
for (int i = 0; i < startingLevelParts; i++)
{
SpawnLevelPart();
}
}
private void Update()
{
if (Vector3.Distance(player.position, lastEndPosition) < PLAYER_DISTANCE_SPAWN_LEVEL_PART){
SpawnLevelPart();
}
}
private void SpawnLevelPart()
{
Transform lastLevelPartTransform = SpawnLevelPart(lastEndPosition);
lastEndPosition = lastLevelPartTransform.Find("EndPosition").position;
}
private Transform SpawnLevelPart(Vector3 spawnPosition)
{
Transform levelPartTransfrom = Instantiate(levelPart1, spawnPosition, Quaternion.identity);
return levelPartTransfrom;
}
void OnBecameInvisible()
{
Destroy(levelPart1);
}
}