简体   繁体   中英

Triggering animations in Unity

Don't know what I'm am doing wrong here, I am trying to trigger an animation in unity Edit: The problem is not that the enemy is destroyed before the animation plays, as the enemy doesn't even get destroyed when

player.cs

 private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Enemy")
        {
            Blue blue = collision.gameObject.GetComponent<Blue>();

            if (action == State.jump || action == State.fall)
            {
                blue.JumpedOn();
                blue.Death();
                jumpVelocity = multiplier * jumpVelocity;
                rb.velocity = Vector2.up * jumpVelocity;
            }
        }
    }

enemy.cs

public void JumpedOn(){
        action = State.death;
        anim.SetBool("Death", true);
    }
    public void Death() {
        Destroy(this.gameObject);
    }

have the condition set in the animator window too, if death = true play animation see here

when I remove the

blue.JumpedOn();

the other lines will run correctly

blue.Death();
jumpVelocity = multiplier * jumpVelocity;
rb.velocity = Vector2.up * jumpVelocity;

I think you should try adding some delay between blue.JumpedOn(); and blue.Death(); .

You need to put a delay between JumpedOn() and Death() because you are calling them in the same frame, the object gets destroyed before the animation has a chance to play. A good way to do this would be coroutines, which are very valuable to use for delaying execution of code.

private IEnumerator coroutine;

IEnumerator WaitAndDestroy(GameObject _callingObject, float _waitTime)
{
    yield return new WaitForSeconds(_waitTime);
    _callingObject.Destroy();
}

public void Death() {
    coroutine = WaitAndDestroy(gameObject, 1.5f);
    StartCoroutine(coroutine);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM