0
点赞
收藏
分享

微信扫一扫

Unity(三十九):非运行状态下脚本播放动画、Animator Override Controller、RuntimeAnimatorController


非运行状态下脚本播放动画

Unity(三十九):非运行状态下脚本播放动画、Animator Override Controller、RuntimeAnimatorController_动画

  • 脚本

using UnityEngine;

namespace Example_01.Scripts
{
[RequireComponent(typeof(Animator))]
public class PlayAnim : MonoBehaviour
{
}
}

// Editor
using System.Linq;
using Example_01.Scripts;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;

namespace Example_01.Editor
{
[CustomEditor(typeof(PlayAnim))]
public class PlayAnimEditor : UnityEditor.Editor
{
private AnimationClip[] _animationClips;
private PlayAnim _script;

private void OnEnable()
{
_script = target as PlayAnim;
Animator animator = _script!.gameObject.GetComponent<Animator>();

// 控制动画器的 AnimatorController 的运行时表示
AnimatorController animatorController = (AnimatorController)animator.runtimeAnimatorController;
// 获取动画列表
_animationClips = animatorController.animationClips;
}

// 当前选择的动画下标
private int _selectedIndex;

// 当前滚动的位置值
private float _sliderValue;

public override void OnInspectorGUI()
{
base.OnInspectorGUI();

// 启动代码块以检查GUI更改
EditorGUI.BeginChangeCheck();

// 获取动画名称列表
string[] displayedOptions = _animationClips.Select(clip => clip.name).ToArray();
_selectedIndex = EditorGUILayout.Popup("动画", _selectedIndex, displayedOptions);

// 滑动条
_sliderValue = EditorGUILayout.Slider("进度", _sliderValue, 0.0f, 1.0f);

// 如果发生更改,结束代码块并更新标签
if (EditorGUI.EndChangeCheck())
{
// 当前使用的动画
AnimationClip animationClip = _animationClips[_selectedIndex];
// 将总时间均匀分布在滚动条上
float time = animationClip.length * _sliderValue;
// 在给定时间针对任何动画属性对动画进行采样
animationClip.SampleAnimation(_script.gameObject, time);
}
}
}
}

Animator Override Controller

RuntimeAnimatorController

  • 脚本

using UnityEngine;

namespace Example_01.Scripts
{
public class SetAnim : MonoBehaviour
{
public Animator animator;

private void OnGUI()
{
if (GUILayout.Button("读取控制器"))
{
RuntimeAnimatorController controller = Resources.Load<RuntimeAnimatorController>("Animator Controller");
animator.runtimeAnimatorController = controller;
}

if (GUILayout.Button("删除控制器"))
{
animator.runtimeAnimatorController = null;
}
}
}
}


举报

相关推荐

0 条评论