- Home /
Melee Attack C# Script Help
Been working on this script for the after noon and I just can't seem to get it to work so I'm reaching out to the community. I've basically set up a trigger on my characters weapon with an invisible collider that will (hopefully) register an attack. At the moment, nothing happens when I click the mouse button, no animation, nothing. Unity gives me a yellow error 'Unreachable Code Detected' for the 'yield return new WaitForSeconds(swingRate);' so there's an error there. This code is part of my main controller code, I'm not gonna past 200+ lines of code but feel free to ask for more code if it's needed. Again, no red errors so I know I'm close... Any assistance you can give me will be awesomeeeeee!
// Melee Attacking Script
IEnumerator MeleeSwing()
{
while(true)
{
if(Input.GetMouseButtonDown(0))
{
anim.SetBool("Attack", true);
meleeTrigger.SetActive(true);
yield return new WaitForSeconds(anim.GetCurrentAnimatorStateInfo(0).length);
meleeTrigger.SetActive(false);
break;
yield return new WaitForSeconds(swingRate);
}
else
{
yield return 0;
}
}
}
Answer by Scutah · Jan 18, 2014 at 04:48 AM
The Unreachable Code Detected is because you have a break before a yield. break will break the the while loop, which also means your function wont return anything. I very rarely use yield so I cannot comment on it.
Okay, what can I use ins$$anonymous$$d for my situation? Basically I want to have a delay after I attack so the player cant keep attacking over and over. I want the animation to finish before allowing another attack, like a 1.5 second delay. I'm new to mecanim as well.
I'm not new to program$$anonymous$$g but I am new to mecanim so i'll do some looking for you
Been trying the last 4 hours to fix it and still no dice... why is program$$anonymous$$g such a bitch?
Here's an example of a delay. In Start(),
attackTimer = 1.5;
In Update(),
if (attackTimer > 0)
attackTimer -= Time.deltaTime;
if (attackTimer < 0)
attackTimer = 0;
Ignore input/attack button if attackTimer != 0 Not the most efficient but something to get you going.
Ok great I'll try to get something working with that. $$anonymous$$an, who would have guessed that a good melee attacking script would be one of the hardest things to code lol