Last active
January 19, 2021 21:48
-
-
Save kankikuchi/6e0433dc0e9584f90f47bd8bec26a039 to your computer and use it in GitHub Desktop.
SimpleAnimationでアニメーション終了後に処理(コールバックの設定)【Unity】
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SimpleAnimationMonoBehaviour.cs | |
// http://kan-kikuchi.hatenablog.com/entry/SimpleAnimation_Callback | |
// | |
// Created by kan.kikuchi on 2020.02.27. | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
/// <summary> | |
/// シンプルアニメーションを持ったMonoBehaviour | |
/// </summary> | |
public class SimpleAnimationMonoBehaviour : MonoBehaviour { | |
//シンプルアニメーションのとそれで使うアニメーションクリップ | |
[SerializeField] | |
private SimpleAnimation _simpleAnimation = null; | |
[SerializeField] | |
private List<AnimationClip> _animationClipList = new List<AnimationClip>(); | |
//現在の状態(アニメーション)名 | |
private string _currentStateName; | |
//アニメーション再生後の処理 | |
private Action _callback; | |
//================================================================================= | |
//初期化 | |
//================================================================================= | |
private void Start(){ | |
//AddClip等のメソッドはAwakeだとエラーが出るので注意 | |
foreach (var animationClip in _animationClipList) { | |
_simpleAnimation.AddClip(animationClip, animationClip.name); | |
} | |
CrossFade("Run"); | |
} | |
//================================================================================= | |
//更新 | |
//================================================================================= | |
private void Update() { | |
//コールバックがあればアニメの終了を判定 | |
if (_callback != null && _simpleAnimation.GetState(_currentStateName).normalizedTime >= 1) { | |
_callback(); | |
_callback = null; | |
} | |
} | |
//================================================================================= | |
//変更 | |
//================================================================================= | |
/// <summary> | |
/// アニメーションをフェードで切り替える | |
/// </summary> | |
public void CrossFade (string stateName, float fadeLength = 0.5f, Action callback = null) { | |
//既に同名のアニメを再生している場合はスルー | |
if (_currentStateName == stateName) { | |
return; | |
} | |
//指定されたアニメーションがあるかチェック | |
if (_simpleAnimation.GetState(stateName) == null) { | |
Debug.LogWarning(stateName + "というアニメーションがありません!"); | |
callback?.Invoke(); | |
return; | |
} | |
//前のコールバックが実行されているかチェック | |
if (_callback != null) { | |
Debug.LogWarning($"{stateName}の再生が開始されたため、{_currentStateName}の再生を中止し、コールバックをすぐに実行します"); | |
_callback(); | |
} | |
//フェードの切り替え開始 | |
_currentStateName = stateName; | |
_callback = callback; | |
_simpleAnimation.CrossFade(_currentStateName, fadeLength); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment