Check if List contains specific object values (JS)

I’m trying to optimise my code:

for (var a = 0; a < GhostObjects.Count; a++) {
   if (GhostObjects[a].name == "GhostObj Pos_" + Current_Pos && GhostObjects[a].transform.position.x < 1) {

As you can see, I’m going through a list and checking to see if there is an object with a name of “GhostObj Pos_34” (If the current pos was 34), and then I’m checking to see if that object has a position of x less than 1.

If both criteria is matched, it will then go ahead and kill the player.

Here lies the problem: as the game progresses, there are more and more Ghost Objects added to the list, and therefore the code becomes slower because it iterates through all of the ghost objects.

Please can you suggest ways I can get around this problem by optimising the code to run at a constant speed whatever the case maybe.

Please note, I have tried List.Contains, but I don’t know how I would insert multiple criteria of the same object into the contains.


You should just make a script, called GhostDeath or something, and attach it to every Ghost object. Much simpler, and doesn’t require a for loop.

Create a empty game object with a bounding box where you want the Ghosts to delete, and then tag it “DeathBox”. Then, just have each Ghost check for collisions with it:

void OnCollisionEnter(Collision c)
    if(c.gameObject.tag == "DeathBox")


It’s also more object oriented (the objects are checking themselves for death).