Search Unity

Tagged based damage receiver.

Discussion in 'Scripting' started by silvabrid, Oct 21, 2016.

  1. silvabrid

    silvabrid

    Joined:
    Aug 12, 2010
    Posts:
    109
    i have a basic damage receiver script that can take damage from any game Object scripted with a damage giver. what i want to do is have a game object with certain tag names to deliver damage.

    Example: enemy tag fires a missile that damages a player but doesn't damage tag named enemy.

    My Code:

    Code (JavaScript):
    1. var hitPoints = 100.0;
    2. var detonationDelay = 0.0;
    3. var explosion : Transform;
    4. var deadReplacement : Rigidbody;
    5.  
    6. function ApplyDamage (damage : float) {
    7.     // We already have less than 0 hitpoints, maybe we got killed already?
    8.     if (hitPoints <= 0.0)
    9.         return;
    10.        
    11.     hitPoints -= damage;
    12.     if (hitPoints <= 0.0) {
    13.         // Start emitting particles
    14.         var emitter : ParticleEmitter = GetComponentInChildren(ParticleEmitter);
    15.         if (emitter)
    16.             emitter.emit = true;
    17.  
    18.         Invoke("DelayedDetonate", detonationDelay);
    19.     }
    20. }
    21.  
    22. function DelayedDetonate () {
    23.     BroadcastMessage ("Detonate");
    24. }
    25.  
    26. function Detonate () {
    27.     // Destroy ourselves
    28.     Destroy(gameObject);
    29.  
    30.     // Create the explosion
    31.     if (explosion)
    32.         Instantiate (explosion, transform.position, transform.rotation);
    33.  
    34.     // If we have a dead barrel then replace ourselves with it!
    35.     if (deadReplacement) {
    36.         var dead : Rigidbody = Instantiate(deadReplacement, transform.position, transform.rotation);
    37.  
    38.         // For better effect we assign the same velocity to the exploded barrel
    39.         dead.rigidbody.velocity = rigidbody.velocity;
    40.         dead.angularVelocity = rigidbody.angularVelocity;
    41.     }
    42.    
    43.     // If there is a particle emitter stop emitting and detach so it doesnt get destroyed
    44.     // right away
    45.     var emitter : ParticleEmitter = GetComponentInChildren(ParticleEmitter);
    46.     if (emitter) {
    47.         emitter.emit = false;
    48.         emitter.transform.parent = null;
    49.     }
    50. }
    51.  
    52. // We require the barrel to be a rigidbody, so that it can do nice physics
    53. @script RequireComponent (Rigidbody)

    how can i do this?