スペースキーで攻撃アニメーションを再生し、判定・効果音・エフェクトを連動させる方法(Unity 6・新Input System対応)
目的
Unity 6 の新Input SystemとAnimator Controllerを使って、以下を実装します。
- スペースキーで攻撃アニメーションを再生
- アニメーションイベントで判定と演出を制御
- StateMachineBehaviourでステートを監視
シーン構成
Hierarchy の構成例
Main Camera
Directional Light
Plane
Player(Capsule)
├── Animator
├── AttackTrigger.cs
├── PlayerAttack.cs
├── Audio Source
├── InputSystem_Actions
└── HitBox(子オブジェクト)




→ プレイヤーオブジェクトにアタッチされたスクリプトとヒエラルキーの構造が確認できます。
Animator 設定
Animator Controller の構成例
- Idle → Attack(Trigger “Attack”)
- Attack → Idle(Exit Time)





→ Animator のステート遷移の全体構成と、AttackステートがTriggerで動く様子がわかります。
ステートに AttackState.cs を追加
- Attackステートを選択
- 「Add Behaviour」で AttackState を追加

→ ステートに StateMachineBehaviour を追加する手順です。
アニメーションイベント設定
Attack アニメーションクリップにイベントを追加
- 0.2秒あたりに EnableHitBox
- 0.7秒あたりに DisableHitBox


→ Animation ウィンドウでイベントを追加する手順が確認できます。
Input System 設定
InputSystem_Actions.inputactions
- Action Map: Player
- Action: Attack
- Type: Button
- Binding: /space

→ InputSystem_Actions での Attack アクションの設定内容です。
スクリプト一覧
AttackTrigger.cs(入力 → アニメーション)
using UnityEngine;
using UnityEngine.InputSystem;
public class AttackTrigger : MonoBehaviour
{
[SerializeField] private InputActionAsset inputActionsAsset;
private InputAction attackAction;
private Animator animator;
void Awake()
{
attackAction = inputActionsAsset.FindAction("Player/Attack");
}
void OnEnable()
{
attackAction?.Enable();
attackAction.performed += OnAttack;
}
void OnDisable()
{
attackAction.performed -= OnAttack;
attackAction?.Disable();
}
void Start()
{
animator = GetComponent<Animator>();
}
private void OnAttack(InputAction.CallbackContext context)
{
animator.SetTrigger("Attack");
}
}
PlayerAttack.cs(イベント処理)
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
public GameObject hitBox;
public AudioSource audioSource;
public GameObject effectPrefab;
public void EnableHitBox()
{
hitBox.SetActive(true);
audioSource?.Play();
if (effectPrefab != null)
Instantiate(effectPrefab, transform.position + Vector3.forward, Quaternion.identity);
}
public void DisableHitBox()
{
hitBox.SetActive(false);
}
}
AttackState.cs(アニメーションステートの監視)
using UnityEngine;
public class AttackState : StateMachineBehaviour
{
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
Debug.Log("Attackステート開始");
}
public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
Debug.Log("Attackステート終了");
}
}
実行と確認
- 再生モードでマウス左クリック
- 以下の処理が実行される:
- アニメーションが再生(Idle → Attack)
- ヒットボックスがON/OFF
- 効果音・エフェクト発動
- AttackStateによりログが表示

拡張ポイント(任意)
拡張機能 | 方法 |
---|---|
プレイヤー移動 | Input System の Moveアクションを使ってRigidbody制御 |
コンボアクション | Animator に複数の Attack ステートを設定 |
ヒット検出 | HitBox に OnTriggerEnter() を実装し、タグで敵を識別 |
訪問数 14 回, 今日の訪問数 1回
ディスカッション
コメント一覧
まだ、コメントがありません