- Home /
Array - SendMessage to two Targets.
The situation is:
I have a melee weapon script - it consists of the Physics Overlap Sphere, in which targets will get Damage, when the Player pushes Fire button. The problem is: I need it to Send Message just to the first two of the Targets (of more specificly: number of enemies determined by Max Targets variable).
FOR NOW:
It simply sends message to ALL Enemies in range. How should I limit it to just two enemies?
The Code:
#pragma strict
public var MeleeRange : float = 5;
public var TheDamage : float = 500;
var TargetsInRange = new Transform[2]; //<-- Number "2" is there for a placeholder.
var MaxTargets : int = 2; //<-- This should be the number of Enemies to SendMessage.
function Update ()
{
var TargetsInRange = Physics.OverlapSphere(transform.position, MeleeRange);
for each (var Target in TargetsInRange)
{
if (Input.GetButtonDown("Fire") && Target.gameObject.transform.tag == "Enemy")
{
Target.SendMessage("ApplyDamageNormal", TheDamage, SendMessageOptions.DontRequireReceiver);
}
}
}
Answer by robertbu · Jul 09, 2014 at 06:20 PM
Try changing your for() to something like this:
for (var i = 0; i < Mathf.Min(TargetsInRange.Length, MaxTargets); i++)
{
var Target = TargetsInRange[i];
if (Input.GetButtonDown("Fire") && Target.gameObject.transform.tag == "Enemy")
{
Target.SendMessage("ApplyDamageNormal", TheDamage, SendMessageOptions.DontRequireReceiver);
}
}
Note I would suggest moving your 'Input.GetButtonDown("Fire")' enclosing everything else in this function. There is no reason to do the Physics.OverlapSphere() if the button did not go down this frame.
Ha! Works like a charm! :D Good thinking with moving Input too - I'll need to keep in $$anonymous$$d to not clutter Update() to much. ;)
Thanks a lot! :)
Actually, you need to detect Input.GetButtonDown() in update, but you want to enclose the rest of your logic. It will be something like:
function Update()
{
if (Input.GetButtonDown("Fire")
{
// The rest of the code goes here
}
}
This way you don't do the Physics.OverlapSphere() or the for() loop unless the button is pressed down. The code above does it every frame.