Removing items from list by OnTriggerExit
Hi, I have certain Items inside a collider, and all the items inside the collider are taken inside a list. But when I take an item outside the collider (And destroying it). It gives me an error, about still trying accesing the item when the item is destroyed.
I believe the error is in the part of "OnTriggerExit", So you don't have to read the entire code
The error is (I think) that the item is not removed from the list.
This is my code:
public class ActivateTextMeshes : MonoBehaviour { public List textMeshes = new List();
void OnTriggerEnter(Collider other)
{
if (other.GetComponentInChildren<TextMesh>() && other.gameObject.tag == "PickableItem")
{
/* ADDS ALL TEXT MESHES TO LIST */
if (!textMeshes.Contains(other.gameObject.GetComponent<TextMesh>()))
{
textMeshes.Add(other.gameObject.GetComponentInChildren<TextMesh>());
}
}
/* CHECKS IF THE PLAYER IS INSIDE THE COLLIDER */
if (other.GetComponent<Collider>().bounds.Contains(player.transform.position))
{
ActivateAllTextMeshes();
}
}
void OnTriggerExit(Collider other)
{
if (!other.GetComponentInChildren<TextMesh>() && other.gameObject.tag == "PickableItem")
{
textMeshes.Remove(other.gameObject.GetComponentInChildren<TextMesh>());
textMeshes.TrimExcess();
}
//If the player exits from the collider
if (other.GetComponent<Collider>().bounds.Contains(player.transform.position))
{
DeactivateAllTextMeshes();
}
}
void ActivateAllTextMeshes()
{
for (int i = 0; i < textMeshes.Count; i++)
{
textMeshes[i].GetComponent<TextMesh>().gameObject.SetActive(true);
}
}
void DeactivateAllTextMeshes()
{
for (int i = 0; i < textMeshes.Count; i++)
{
textMeshes[i].GetComponent<TextMesh>().gameObject.SetActive(false);
}
}
}
Checked. Actually the line 29 to 32 works fine :)
Answer by Zeronev · Nov 02, 2015 at 09:03 PM
Fixed this with this Godly Loop:
void RemoveUnnesessaryItems()
{
for (int i = 0; i < textMeshes.Count; i++)
{
if (textMeshes[i] == null)
{
textMeshes.Remove(textMeshes[i]);
}
}
}
Answer by Fire_Cube · Nov 02, 2015 at 07:27 PM
Line 22, I think there shouldn't be the '!', but line 29 i think there should be one. Not sure but can be just this.