Search Unity

Using OnTriggerEnter with BoxCollider to Destroy and Object

Discussion in 'Scripting' started by trevorchandler, Jun 4, 2009.

  1. trevorchandler

    trevorchandler

    Joined:
    May 16, 2009
    Posts:
    121
    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. trevorchandler

    trevorchandler

    Joined:
    May 16, 2009
    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 ... :eek:(


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