Unity Community


Results 1 to 2 of 2

  1. Posts
    121

    Using OnTriggerEnter with BoxCollider to Destroy and Object

    Hello all,

    I have this simple script ...

    static var Count : int = 0;
    var CollectSound : AudioClip;

    function OnTriggerEnter (hit : Collider){
    Destroy(hit.gameObject);
    Count++;
    message="We Collided";
    audio.PlayOneShot(CollectSound);
    }

    It is applied to a rotating cube. The cube is using the BoxCollider and is set to 'Trigger'.

    I am trying to make it destroy the cube and play the sounds, but I cant get the message to show up, so I must be using the collider incorrectly.

    Any ideas here?

    Thanks,

    Trevor


  2. Posts
    121
    ANSWER:

    Everyone, I am posting the answer.

    I haven't a single response from anything i've posted, so maybe this will set a trend.

    *** Or maybe people just don't like me ... (


    Code:  
    1. // Set a counter so you can keep score
    2. static var Count : int = 0;        
    3.  
    4. // Allows you so choose sound clip
    5. var CollectSound : AudioClip;  
    6.  
    7. // Will detect any type of collision
    8. // Make sure you set isTrigger on the gameObject this is attached to
    9. function OnTriggerEnter (other : Collider) {
    10.  
    11.  
    12.         // Counter integer we are keeping track of how many objects we have collided with in. Good for score keeping, etc...
    13.     Count++;                                            
    14.  
    15.         // For choosing an audio sound to play when collision occurs. Make sure you have also added an audio source on the gameObject.
    16.     audio.PlayOneShot(CollectSound);    
    17.  
    18.     print(Count);                                        
    19.  
    20.         // Destroys the item you collided with
    21.     Destroy(gameObject);                    
    22.     }

    I hope this helps someone.

    This was very basic, but you wouldn't know by reading the scripting guide that just gives you a single line. And the example they post is above the simplest use (or sometimes there are none at all)

    Don't get me wrong, I love unity3d, it's just been challenging to learn to do things even after reading all the docs and going through all posted tutorials.

    Thanks,

    Trevor

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •