簡體   English   中英

如何在 Unity 上玩死亡 animation?

[英]How can i play a death animation on Unity?

我想對我的敵人玩死 animation。 基本上,他有一個空閑的 animation,我想在他死時玩死亡 animation,一兩秒后,游戲對象被刪除。 我是編碼新手,所以一個基本的解決方案會更好:)。 這是我的編碼:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyHealthManager : MonoBehaviour {

    public int enemyHealth;
    public GameObject deathEffect;
    public int pointsOnDeath;

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () 
    {
        if (enemyHealth <= 0) 
        {
            Instantiate (deathEffect, transform.position, transform.rotation);
            ScoreManager.AddPoints (pointsOnDeath);
            Destroy (gameObject);

        }
    }




    public void giveDamage(int damageToGive)
    {
        enemyHealth -= damageToGive;
    }
}

您可以添加一個名為 PlayAnimationAndDestroy() 的 function 作為 void 並在其中放置 Destroy (this.gameObject, 2f) 然后 animator.Play("deathAnim");

在 Destroy 中,逗號后面的數字是 Unity 等待銷毀 object 的時間,因此您需要在時間軸中檢查 animation 的持續時間並將該持續時間放入 Destroy ()。

另一種方法是按下 animation 末尾的記錄按鈕並更改公共變量。 在腳本中,您將放置一個簡單的 if(),如果該變量已更改,您將銷毀 object。

The third way is to use animation events ( https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html ) but for your usage the first two options are easier:)

歡迎來到統一! 在你的項目中使用AnimatorController和你想要死的GameObject上的相應Animator組件也將成為你的朋友。

您可以 在此處查看Unity 關於動畫控制器的精彩教程,但基本上,它是一台 state 機器。 Based on what state your object is in, you can control which game object animations are active and you can set triggers in your game logic to trigger a transition to another state.

這對於觸發死亡動畫等情況非常有用。

在您的情況下,您需要一個 state 用於idle ,一個 state 用於death 您的deathidle的 state 之間存在聯系。

您將設置一個名為die的觸發器。 當你的die觸發器在游戲邏輯中被觸發時,你可以讓 state idle只移動到 state death

因此,第 1 步:您將從編輯器中創建一個新的AnimatorController Scriptable Object,然后在Animator window 中對其進行編輯。 使用所需的動畫制作所需的 state 機器,並將ScriptableObject保存在項目文件夾中。

第 2 步:在您想要影響的GameObject上添加一個Animator組件。 它有一個AnimatorController組件 - 在此處添加您新創建的 controller。

第 3 步:在您的游戲邏輯腳本中,您將引用該Animator組件:

...
public int enemyHealth;
public GameObject deathEffect;
public int pointsOnDeath;
public Animator animComponent;
...

然后當你達到你的條件時,你會做這樣的事情:

if (enemyHealth < 0){
    animComponent.SetTrigger("die");
}

然后您的AnimatorController將從您之前的 state 移動到death ,您設置的 animation 將播放。

祝你好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM