Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Help destroying an object that is off limits

Discussion in 'Scripting' started by SirMarley, Aug 2, 2014.

  1. SirMarley

    SirMarley

    Joined:
    Jul 26, 2014
    Posts:
    115
    Hi guys...

    I have a couple of planes with a Z of 3.25, scrolling down, so it looks like a 2D game.
    I also have a Space Ship that moves left and right and shoots
    And I am in the process of setting up the enemies (they show up each 2 seconds)

    My problem is that once the bullets and the enemies go out of sight, they still in the game...

    I have try destroying them this way:
    Code (CSharp):
    1. if (enemy.transform.position.y < -9.05)
    2.             {
    3.                 Destroy(enemy);
    4.             }
    But, as a result, I had the prefab deleted from my assets (weird)

    How I can set it up? (I tried also with Destroy(this.gameObject) and OnBecameInvisible but none of them worked)
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    Well, it's not actually weird because you destroyed the prefab. What you need to do instead is instantiate the prefab, and destroy the instance.

    --Eric
     
  3. SirMarley

    SirMarley

    Joined:
    Jul 26, 2014
    Posts:
    115
    I did... well.. I think I did...
    This is what I have...
    The prefab´s name is Enemy1 and is attached to the script
    the Script is:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Enemy : MonoBehaviour {
    5.  
    6.     public GameObject enemy;
    7.     public float myTimer = 2;
    8.  
    9.     void Update()
    10.     {
    11.         myTimer = myTimer -= Time.deltaTime;
    12.         if (myTimer <= 0)
    13.         {
    14.                 Enemy1();
    15.                 myTimer = 2;
    16.         }
    17.     }
    18.  
    19.     void Enemy1()
    20.     {
    21.         GameObject myPrefab = (GameObject)Instantiate(enemy, new Vector3(Random.Range(-8.5f, 8.5f), 5f, 3.25f), Quaternion.identity);
    22.             if (enemy.transform.position.y < -9.05)
    23.             {
    24.                 Destroy(myPrefab);
    25.             }
    26.     }
    27. }
    (this way it does not destroy anything)