オブジェクトの位置をリセットするボタンを作る(Unity)

  1. HierarchyにUI→Buttonでボタンを作る。

  2. ボタンにスクリプトをアタッチして、以下のように記載する。クラス名は自分が作ったものを使う。using UnityEngine.UI;は忘れがちなので注意。Start()で初期位置を取得しておいて、クリックされた際にその位置に戻す。回転や速度を持っていた場合も0にする。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PosReset : MonoBehaviour
{
    public GameObject car;
    private Vector3 pos;

    // Start is called before the first frame update
    void Start()
    {
        pos = car.transform.position;
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void OnClick()
    {
        Rigidbody rb = car.transform.GetComponent<Rigidbody>();

        car.transform.position = pos;
        car.transform.rotation = Quaternion.identity;
        rb.velocity = new Vector3(0, 0, 0);
        Debug.Log("Pos Reset");
    }
}
  1. ButtonのInspectorのさっきアタッチしたスクリプトのCarに、場所をリセットしたいオブジェクトをアタッチする。

  2. ButtonのInspectorのOn Click()で、+を押して処理を追加、Buttonの"オブジェクト"をアタッチ、先ほどのスクリプト内の実行させたい処理(OnClick())を設定する。処理に対してはスクリプトもアタッチできるが、オブジェクトをアタッチする必要がある点に注意。スクリプトをアタッチしているとOnClick()が見つからない。