【Unity】ボタン押下時のアニメーション

ボタンを押した際の「ボタンを押した感」を超簡単に設定しましょう。

このようにボタンを押した際にボタンが凹み、ボタン押した感が演出されます。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PushButtonAnime : MonoBehaviour
{
    private Vector3 posi = new Vector3(0f,0f,0f);

    public void OnButton(){ //ボタン押した時
        if(posi==new Vector3(0f,0f,0f)){
            posi = this.transform.localPosition; //ボタンを押す前の座標
        }
        this.transform.localPosition = posi + new Vector3(5,-5,0); //ボタンを右下に移動
    }

    public void OutButton(){ //ボタンから離れたとき
        this.transform.localPosition = posi; //ボタンを元の位置に戻す
    }
}

PushButtonAnime.csというScriptファイルを作成し、上記のコードを貼り付けます。
ボタンのオブジェクトにPushButtonAnime.csをドラッグ&ドロップで追加
Add Component⇒Event⇒EventTriggerを追加
EventTriggerのAddNewEventTypeでPointerDownとPointerUpを追加
PointerDownにオブジェクトをセットしてPushButtonAnime.OnButtonを設定
PointerUpにオブジェクトをセットしてPushButtonAnime.OutButtonを設定

このようになります。
これで設定完了です。
ボタンを押すとボタンの座標が右下に僅かに移動して凹んでるように見え、離すと元の位置に戻ります。

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です