Why are objects being inconsistently destroyed with this projectile script?
Basically, what I am trying to accomplish is for targets consisting of a cube with a sphere on top to be destroyed when either the sphere or the cube is hit. I have a script that spawns the targets called Level1Controller.cs and within it a list called spawnedTargets that contains all spawned targets.
When a collision is detected, I grab the x and z coordinates of the target with which the bullet collided, and loop through all objects in spawnedTargets looking for targets with the same x and z coordinates, since the sphere and cube of every target set share x and z coordinates. I use Destroy() to destroy every matching object.
The issue I'm encountering is that almost always at least 1 sphere + cube target set does not destruct on being hit by a bullet, and when one such set is hit, no further sets are properly destroyed when hit by a bullet. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour {
public float TimeToLive = 5f;
GameObject referenceObject;
Level1Controller referenceScript;
List<GameObject> spawnedTargets;
int eIncrementor;
private void Start()
{
referenceObject = GameObject.FindGameObjectWithTag("Manager"); // reference to Manager object
referenceScript = referenceObject.GetComponent<Level1Controller>(); // reference to Level1Controller attached to Manager
spawnedTargets = referenceScript.spawnedTargets; // reference to spawnedTargets of Level1Controller
eIncrementor = referenceScript.eIncrementor; // reference to eIncrementor of Level1Controller
Destroy(gameObject, TimeToLive);
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Target")
{
if ( eIncrementor == 9) // temporarily set to always, press t to enter this level
{
Manager.targetsHit++;
float otherXCoord = other.gameObject.transform.position[0]; // save X and Z coordinates of hit target
float otherZCoord = other.gameObject.transform.position[2];
foreach (GameObject obj in spawnedTargets) {
if (obj.transform.position[0] == otherXCoord && obj.transform.position[2] == otherZCoord) { // if both x and z coordinates match, they belong to the same target sets
Destroy(obj); // always at least 1 target set remains, not sure why
// spawnedTargets.Remove(obj); - when this line is added, only the hit target is detonated
}
}
}
else
{
Manager.targetsHit++;
Destroy(other.gameObject);
}
}
else if (other.tag == "Obstacle")
{
Manager.timeValue = Manager.timeValue - 5;
Destroy(other.gameObject);
}
}
}