【问题标题】:Unity 2D - How to play death animation prefabUnity 2D - 如何播放死亡动画预制件
【发布时间】:2015-09-19 16:50:49
【问题描述】:

我创建了一个带有精灵表动画的预制件,我想在玩家死亡时播放它。我通过在场景中拖动预制件来检查它是否正在工作,并且它可以无休止地循环播放精灵表的每一帧。

现在我想在玩家死亡时播放这个预制件,并在它结束后销毁它,但到目前为止我只能将它放置在玩家死亡的地方,并且它会永远留在那里。发生这种情况时也会出现一些错误。

这是死亡脚本:

 public class DmgByCollisionEnemy : MonoBehaviour {

    public GameObject deathAnimation;

    void Die() {
        deathAnimation = (GameObject) Instantiate(deathAnimation, transform.position, transform.rotation);
        //Destroy(deathAnimation);
        Destroy(gameObject);
    }
}

我通过在Unity界面中拖动一个预制件来设置deathAnimation。

Die() 方法触发时出现的错误是

UnassignedReferenceException: The variable deathAnimation of DmgByCollisionEnemy has not been assigned.
You probably need to assign the deathAnimation variable of the DmgByCollisionEnemy script in the inspector.

那么我该如何正确地做到这一点呢?

【问题讨论】:

    标签: c# unity3d unity3d-2dtools


    【解决方案1】:

    您可以尝试向您的死亡动画对象添加简单的销毁脚本,该脚本会在一段时间后销毁对象或在动画中触发它(Unity Manual: Using Animation Events)。当您实例化对象时,它将出现在所需的位置,并且无论“主”对象如何,它都会被销毁。

    像这样销毁脚本:

    void DestroyMyObject() 
    { 
       Destroy(gameObject); 
    }
    

    在时间之后运行的脚本:

    void Start() 
    {
        Invoke ("DestroyMyObject", 1f);
    }
    
    void DestroyMyObject()
    {
        Destroy(gameObject);
    }
    

    生成脚本:

    using UnityEngine;
    using System.Collections;
    
       public class SpawnExtra : MonoBehaviour {
    
       public GameObject deathAnimation;
    
       public static SpawnExtra instance;
    
       void Start () 
       {
            instance = this;
       }
    
       public void SpawnDeathAnimation(Vector3 position)
       {
            Instantiate (deathAnimation, position, Quaternion.identity);
       }
    }
    

    当你想像这样生成其他对象时可以使用它:

    SpawnExtra.instance.SpawnDeathAnimation (transform.position);
    

    现在您必须添加游戏对象,例如 ExtrasController,在其上添加脚本,然后您可以生成任何您想要的东西。记得在检查器中拖放动画预制件。

    【讨论】:

    • 但是如何制作类似计时器的代码? for 循环对此不起作用
    • 有两种有用的方法。协程和调用。我建议您使用 Invoke。像这样: Invoke("DestroyMyObject", 1f); - 此代码将在 1 秒后运行 DestroyMyObject 函数。进行了一些编辑以更好地显示示例。
    • 效果很好,但我仍然收到此错误(或警告?它带有红色 (!) 符号) - “DmgByCollisionEnemy 的变量 deathAnimation”尚未分配。这是公共对象,我通过在 Unity UI 中拖动动画预制件来定义它
    • 您是否在播放模式下进行了拖放操作?记住您必须在播放模式下进行更改,这是最常见的问题:) 只是要求确定。
    • 不,它不在播放模式,我认为问题是因为预制件是用 Instantiate 方法克隆的,但我不知道如何修复它
    猜你喜欢
    • 2021-03-25
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    相关资源
    最近更新 更多