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

destroying prefabs after instantiation scripts

Discussion in 'Scripting' started by cristo, Dec 9, 2014.

  1. cristo

    cristo

    Joined:
    Dec 31, 2013
    Posts:
    265
    Hi, I'm trying to have prefab music notes come out of my guitar melee weapon and it's working. I'd like the notes to be destroyed after a few seconds, but they stay in the scene.

    I tried adding a destroy game object line in the java melee script after instantiation of the musicnote, but it only destroyed the guitar.
    Then I tried adding a destroy gameobject script, this time in C# to the prefab musicnote.

    No errors popped up but the musicnote clones just keep coming and none get destroyed. Any feedback on what I'm doing wrong would be great.



    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var TheDamage : int = 50;
    4. var Distance : float;
    5. var MaxDistance : float = 1.5;
    6. var Mockron_Guitar : Transform;
    7. var MusicNote : GameObject;
    8. function Update()
    9. {
    10.         if (Input.GetButtonDown("Fire1"))
    11.         {
    12.         animation.Play ("Melee");
    13.         }
    14.  
    15. var hit : RaycastHit;
    16. if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), hit))
    17. {
    18.     Distance = hit.distance;
    19.     if (Distance < MaxDistance)
    20.     {
    21.     hit.transform.SendMessage("ApplyDamage", TheDamage, SendMessageOptions.DontRequireReceiver);
    22.     var instance : GameObject = Instantiate(MusicNote, transform.position, transform.rotation);
    23.     }
    24. }
    25. }
    26.  
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Destroy : MonoBehaviour {
    5.  
    6.     GameObject MusicNote;
    7.  
    8.  
    9.     // Update is called once per frame
    10.     void Start () {
    11.  
    12.         Destroy (gameObject);
    13.     }
    14.    
    15. }
    16.  
     
  2. jgodfrey

    jgodfrey

    Joined:
    Nov 14, 2009
    Posts:
    564
    You should be able to simply register the object to be destroyed in a few seconds - immediately after creating it.

    So, right after you instantiate the new object, just add something like:

    Code (CSharp):
    1. Destroy (instance, 2);
    Jeff
     
  3. cristo

    cristo

    Joined:
    Dec 31, 2013
    Posts:
    265
    Thanks Jeff, that worked. Thanks for teaching me that!