Game Development Reference
In-Depth Information
In this case, we are going to use Broadcast Message to yell specifically to the
object that has entered the collider. However, this still carries some benefits
since we just shout the message, and the object figures out which script
needs to hear it.
Step 19: Create the DoDamage function. Include a sort of timer in this
function so that if inTrigger is active, it continues to damage the player.
var damageAmount : int;
private var inTrigger : boolean;
function OnTriggerEnter (other:Collider){
if (other.gameObject.tag == “Player”){
inTrigger = true;
DoDamage (other.gameObject);
}
}
function OnTriggerExit (other:Collider){
inTrigger = false;
}
function DoDamage (target : GameObject){
while (inTrigger){
target.BroadcastMessage(“ApplyDamage”,
damageAmount);
yield WaitForSeconds (2);
}
}
Why?
We're using our old trick of a while statement so that as long as the
inTrigger is true (which is set earlier by setting it to true when an object
with tag “Player” enters the trigger), every 2 seconds Unity fires the
command that says “get target (which is the object that collided with
the trigger) and broadcast the message “ApplyDamage” along with the
parameter of how much damage to subtract (damageAmount).
In this case “target” will always be FPC_AegisChung, which also has
attached to it the HealthEngineScript. Remember that within this script
is a function called ApplyDamage that has a parameter of damage:int.
When target “hears” this broadcast message and the parameter of the
damageAmount, it will subtract the damage amount from the current
health value (check out the HealthEngineScript for review).
The cool thing here is that we didn't have to tell the object what script to
use. The object itself received the message and then passed it along to
its components. If a component couldn't do anything with it, it ignores it.
But when a component recognizes the message (like HealthEngineScript),
it obeys.
 
Search WWH ::




Custom Search