Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Destroy gameObject from another script

Discussion in 'Scripting' started by Newtro, Jul 6, 2020.

  1. Newtro

    Newtro

    Joined:
    Nov 14, 2019
    Posts:
    2
    Hi, I'm having trouble trying to destroy the Enemy game object (Script 2) from Script 1, wich is a script containing common enemy data.

    Script 1:
    Code (csharp):
    1.  
    2. public class BaseEnemy : MonoBehaviour
    3. {
    4.     [SerializeField]
    5.     public int health = 4;
    6.     public int speed = 0;
    7.  
    8.     public void TakeDamage(int damage)
    9.     {
    10.         health -= damage;
    11.         Debug.Log("Damage Taken");
    12.        
    13.         if (health <= 0)
    14.         {
    15.             Destroy(??);
    16.         }
    17.     }
    18. }
    Script 2:
    Code (csharp):
    1.  
    2. public class EnemyPlayerFollow : BaseEnemy
    3. {
    4.  
    5.     public Transform player;
    6.     private Rigidbody2D rb;
    7.     private Vector2 movement;
    8.  
    9.     void Start()
    10.     {
    11.         rb = this.GetComponent<Rigidbody2D>();
    12.     }
    13.  
    14.     void Update()
    15.     {
    16.         Vector3 direction = player.position - transform.position;
    17.         float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    18.         rb.rotation = angle;
    19.         direction.Normalize();
    20.         movement = direction;
    21.  
    22.         //if (health <= 0)
    23.         //{
    24.         //    Destroy(gameObject);
    25.         //}
    26.     }
    27.  
    28.     private void FixedUpdate()
    29.     {
    30.         moveCharacter(movement);
    31.     }
    32.  
    33.     //public void TakeDamage(int damage)
    34.     //{
    35.     //    health -= damage;
    36.     //    Debug.Log("Damage Taken");
    37.     //}
    38.  
    39.     void moveCharacter(Vector2 direction)
    40.     {
    41.         rb.MovePosition((Vector2)transform.position + (direction * speed * Time.deltaTime));
    42.     }
    43. }
    What I want to know, is how to modify Script 1 to Destroy Script 2 when health <=0.

    Thanks.
     
  2. Newtro

    Newtro

    Joined:
    Nov 14, 2019
    Posts:
    2
    Was actually easy:
    Destroy(this.gameObject)