Search Unity

My projectiles aren't destroying them selves, help!

Discussion in 'Scripting' started by BenHenriques, Apr 15, 2021.

  1. BenHenriques

    BenHenriques

    Joined:
    Apr 6, 2021
    Posts:
    44
    So heres my projectile script, I used Brackey's tutorial for it since I am pretty new to unity, and I have an impact animation set up so after it impacts it should do the animation and desrtoy it self. The final frame of the impact effect stays in game and the projectile doesn't destroy it self even though I tell it to in the script. Not sure if my problem is with the projectile not destroying itself or if its my animation, thanks in advance!
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ProjectileBehaviour : MonoBehaviour
    6. {
    7.     public float Speed = 20f;
    8.     public int damage = 20;
    9.     public Rigidbody2D rb;
    10.     public GameObject impactEffect;
    11.  
    12.     void Start()
    13.     {
    14.         rb.velocity = transform.right * Speed;
    15.     }
    16.  
    17.     void OnCollisionEnter2D(Collision2D hitInfo)
    18.     {
    19.         Enemy enemy = hitInfo.transform.GetComponent<Enemy>();
    20.         if (enemy != null)
    21.         {
    22.             enemy.TakeDamage(damage);
    23.         }
    24.        
    25.         Instantiate(impactEffect, transform.position, transform.rotation);
    26.  
    27.         Destroy(gameObject);
    28.     }
    29. }
    30.  
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    You are instantiating impactEffect, but you aren't destroying it. Either you have to make it a child of the projectile, or just need to destroy it along with the projectile.
     
  3. BenHenriques

    BenHenriques

    Joined:
    Apr 6, 2021
    Posts:
    44
    Ohh okay thank you!
     
  4. BenHenriques

    BenHenriques

    Joined:
    Apr 6, 2021
    Posts:
    44
    Update, I got it working, thanks so much!
     
  5. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188