【Unity】动作游戏开发实战详细分析-14-动画事件
基本思想
我们可以在动画组件中为动画添加事件,事件函数名会调用在该游戏对象下所有脚本中的同名同参数的无返回值函数,本篇主要介绍通过资源配置来对动画的事件资源进行生成控制。
代码实现
首先是挂在游戏对象上的动画事件函数,它需要一个id,ID对应了需要调用的游戏资源
public class AnimationEventReceiver : MonoBehaviour
{
void AnimationEventTrigger(int id)//接收动画事件绑定函数
{
AnimationEventConfigurator.InstantiateAnimationEventItem(gameObject, id);
}
}
其次,我们通过基础ScriptableObject来生成资源文件
内部类
- 资源信息类
- 动画事件实例信息类
公开字段:资源信息
以及一个静态函数,也就是上面的脚本调用的动画事件函数,通过加载资源配置来加载资源,并生成对象
这里只是一个参考,如果需要运用到项目中,需要自行扩展
[CreateAssetMenu(fileName = "AnimationEventConfigurator", menuName = "YourProjName/AnimationEventConfigurator")]
public class AnimationEventConfigurator : ScriptableObject
{
[Serializable]
public class CategoryInfo//使用分类便于配置
{
public string category;
public List<AnimationEventItem> animationEventInfoList = new List<AnimationEventItem>();
}
[Serializable]
public class AnimationEventItem//动画事件实例信息
{
public int id;
public string resourcePath;//资源路径
public Vector3 positionOffset;
public Vector3 rotateOffset;
}
public CategoryInfo[] categoryInfoArray;
public static GameObject InstantiateAnimationEventItem(GameObject sender, int id)
{
const string CONF_RES_PATH = "AnimationEventConfigurator";//配置路径
var conf = Resources.Load<AnimationEventConfigurator>(CONF_RES_PATH);//获取配置
for (int i = 0; i < conf.categoryInfoArray.Length; i++)
{
var categoryItem = conf.categoryInfoArray[i];
for (int j = 0, jMax = categoryItem.animationEventInfoList.Count; j < jMax; j++)//获事件
{
var eventItem = categoryItem.animationEventInfoList[j];
if (eventItem.id == id)//比较ID
{
var instantiateGO = Instantiate(Resources.Load<GameObject>(eventItem.resourcePath), sender.transform.position, sender.transform.rotation);
var sender_rotation = sender.transform.rotation;
instantiateGO.transform.position += sender_rotation * eventItem.positionOffset;
instantiateGO.transform.eulerAngles += sender_rotation * eventItem.rotateOffset;//设置偏移
return instantiateGO;
}
}
}
return null;
}
}