Script doesn't call method from other script
I have a problem, I want to make that when the player enters the trigger box of an enemy, it activates the attack animation of that enemy, and in a frame in the middle of the animation, the method "OnExplode" is executed, which is already defined in its own script. However, I have achieved that when the player approaches the animation plays, but the method of the other script is not executed. I have added an event in the animation (in an intermediate frame) that executes the method "Attack()".
Does anyone know what may be wrong? It's from a online course and I downloaded the teacher's files, but it has the code exactly like me and the same thing happens.
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "Player")
{
if (readyToAttack)
{
var explode = collision.GetComponent<Explode>() as Explode;
explode.OnExplode();
}
else
{
GetComponent<Animator>().SetInteger("AnimState", 1);
}
}
}
private void OnTriggerExit2D(Collider2D collision)
{
readyToAttack = false;
GetComponent<Animator>().SetInteger("AnimState", 0);
}
void Attack()
{
readyToAttack = true;
}
Do you get any error in the console? Have you tried to use Debug.Log
to check the value of readyToAttack
and check if you enter the various conditions inside OnTriggerEnter2D ?
I haven't got any console errors, and I've tried it the Debug.Log
and for some reason it doesn't enter on the part of the first if (readyToAttack). But when I put the Debug.Log in the method void Attack() it returns the true value of the readyToAttack = true.
maybe it is getting called the ontriggerexit just after your attack method is being called? i would suggest leaving a debug.log with the readyToAttack value and see when it is getting modified.
Answer by whitegrimreaper_ · Jan 31, 2019 at 11:03 PM
Are you actually calling the Attack() function anywhere? It looks as though in
if (readyToAttack) {
...
}
the variable is most likely set to false, preventing the code from following through with the
var explode = collision.GetComponent<Explode>() as Explode;
explode.OnExplode();
Have you tried adding a Debug.Log()
on the line above var = explode
to see if the code is getting to that branch?
" I have added an event in the animation (in an intermediate frame) that executes the method "Attack()"."
also he answered your second question in the comments.