0
\$\begingroup\$

My script isn't deleting this game object once it reaches a certain position in my game. This is my script:

public float left;

public GameObject enemyLeft;

void Start ()
{
    enemyLeft= GameObject.Find("Enemy Left");
}

void Update()
{
    if (transform.position.x < left)
    {
        Destroy (enemyLeft);
    }
}

enemyLeft is a prefab gameObject that is being spawned in by my spawner.

This is the script where I intend to Destroy the game object:

    public float left;

    public GameObject[] enemiesLeft;

    void Update()
    {
        for (int i = 0; i < enemiesLeft.Length; i++) {

            if (enemiesLeft[i].transform.position.x < left) {
                Destroy (enemiesLeft[i]);
            }
        }
    }

Why isn't it deleting the game object?

\$\endgroup\$
1
  • \$\begingroup\$ Please clarify your question. You want to destroy the enemy once the enemy gets to a certain position, or you want to destroy whatever object this script is attached to whenever the enemy reaches a certain position? \$\endgroup\$ Aug 24, 2016 at 18:09

1 Answer 1

1
\$\begingroup\$

Calculate position of enemyLeft instead of script holding object.

   void Update()
    {
        if (enemyLeft.transform.position.x < left)
        {
            Destroy (enemyLeft);
        }
    }
\$\endgroup\$
7
  • \$\begingroup\$ Thank you it worked :), what if I wanted to add a number of how many enemies I want to destroy rather than copy and pasting below the code and renaming it. :) \$\endgroup\$ Aug 24, 2016 at 18:21
  • \$\begingroup\$ For shortcut, use array of enemies. public GameObject[] enemyLeft; Use a loop to get and check if any of them crossed left position, then destroy. Destroy (enemyLeft[i]); You will end up losing objects in array. So should take a long term solution. \$\endgroup\$ Aug 24, 2016 at 18:33
  • \$\begingroup\$ Okay thank you for the reply, I tried out what you said but it doesn't seem to work it doesn't delete anything...again. :(. If you look above I have edit my question and you can see the second edit. Thank you :) \$\endgroup\$ Aug 24, 2016 at 18:40
  • \$\begingroup\$ You are not getting any objects for checking and destroying in the Start(). Also get objects with tag instead of name. \$\endgroup\$ Aug 24, 2016 at 18:47
  • \$\begingroup\$ sorry i'm a bit confused \$\endgroup\$ Aug 24, 2016 at 18:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .