Here’s my code:
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class RadarScript : MonoBehaviour
{
public List<GameObject> TrashItems;
public GameObject Collectibles;
public float Distance;
public float NearestDistance = 100000;
public TextMeshPro TextObject;
public GameObject NearestObject;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
TrashItems = new List<GameObject> (GameObject.FindGameObjectsWithTag("Trash"));
}
void LateUpdate() {
for (int i = 0; i < TrashItems.Count; i++)
{
if (TrashItems[i] != null) {
Distance = Vector3.Distance(transform.position, TrashItems[i].transform.position);
if (Distance < NearestDistance) {
NearestDistance = Distance;
NearestObject = TrashItems[i];
}
TextObject.text = "Distance: " + Vector3.Distance(transform.position, NearestObject.transform.position);
}
}
}
}
It all works perfectly fine, but I have another script that deletes one of the trash items whenever they are collected. When the item gets deleted, I get this error:
I assume it is because the for loop is trying to access a destroyed gameobject, but I have no clue how to fix it. I have tried removing the object from the list when I destroy it, and I have tried setting up the if statement to make sure the object is still there.
I’m newish to unity so I can believe there’s something simple I’m missing. Any help is much appreciated.