Unity 2D-如何玩死亡动画预制
本文关键字:动画 何玩死 2D- Unity | 更新日期: 2023-09-27 18:00:42
我已经用精灵表中的动画创建了一个预制,我想在玩家死亡时播放它。我通过在场景中拖动预制件来检查它是否正常工作,并且它是否在循环中无休止地正确播放精灵表的每一帧。
现在我想在玩家死亡时玩这个预制游戏,在它结束后摧毁它,但到目前为止,我只能把它放在玩家死亡的地方,它永远留在那里。此外,当这种情况发生时也会出现一些错误。
这是死亡脚本:
public class DmgByCollisionEnemy : MonoBehaviour {
public GameObject deathAnimation;
void Die() {
deathAnimation = (GameObject) Instantiate(deathAnimation, transform.position, transform.rotation);
//Destroy(deathAnimation);
Destroy(gameObject);
}
}
我通过在Unity界面中拖动一个预制件来设置死亡动画。
当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.
那么我该如何正确地做到这一点呢?
您可以尝试向您的死亡动画对象添加简单的销毁脚本,该脚本会在一段时间后销毁对象或在动画中触发它(Unity Manual:使用动画事件)。当您实例化对象时,它将出现在所需的位置,并且它将被销毁,而与"主"对象无关。
销毁这样的脚本:
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,在上面添加脚本,你就可以生成你想要的任何东西。记得拖动&在检查器中放置动画预制件。