I'm currently trying to add a melee-slash attack to my Sidescroller.
For that I decided to to have an invisible box-colliders infront of my character. My idea is to activate it when the attack-key is pressed and leave it active for the duration of the attack before turning it inactive again.
I know from a previous attempt with a dash instead (didn't work out on the movement for it) that my code for the attack-triggering in the player-script works just fine, so now in my box-collider infront of the player I have:
public GameObject Player;
//public GameObject Box;
bool attack = false;
//Collider c;
void Awake ()
{
Player = GameObject.FindGameObjectWithTag ("Player");
//Box = GameObject.FindGameObjectWithTag ("AttackBox");
gameObject.collider.enabled = false;
}
void Update ()
{
Player pstats = Player.GetComponent<Player>();
attack = pstats.attacking;
if (!attack)
{
gameObject.collider.enabled = false;
}
if (attack)
{
gameObject.collider.enabled = true;
}
}
And in my Enemy script I have
void OnTriggerEnter(Collider collision)
{
Player pstats = Player.GetComponent<Player>();
if (collision.gameObject.tag == "Player") {
collision.gameObject.GetComponent<Player>().PlayerHit();
}
if (collision.gameObject.tag == "AttackBox")
{
pstats.CurrentEXP += 25;
EnemyDeath ();
}
}
Though the hit isn't recognized.
The issue I see is that probably the OnTriggerEnter is the issue since the Enemy tends to be allready inside the attack-box collider when the attack is triggered. I tested a bit with the Debug-Log and the box is activated at least, so it should really be just the issue of calling the Trigger at the right time.
Are there any alternatives to OnTriggerEnter that would be working better?
edit: I tried adding this right below my collision-part in the enemy-script:
void OnTriggerStay(Collider collision)
{
Player pstats = Player.GetComponent<Player> ();
if (collision.gameObject.tag == "AttackBox")
{
pstats.CurrentEXP += 25;
EnemyDeath ();
}
}
void OnTriggerExit(Collider collision)
{
Player pstats = Player.GetComponent<Player> ();
if (collision.gameObject.tag == "AttackBox")
{
pstats.CurrentEXP += 25;
EnemyDeath ();
}
}
Though the hit is still not recognized.