(Unity)カーソル&クリックでオブジェクトを変化させる方法3(Raycastの活用)

(スクリプト)

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

public class CurcorClick_3 : MonoBehaviour
{
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;

            // ★ポイント
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if(Physics.Raycast(ray,out hit))
            {
                GameObject target = hit.collider.gameObject;

                if(target.CompareTag("Box"))
                {
                    target.transform.Translate(new Vector3(2, 0, 0));
                }
            }
        }
    }
}

(設定)

・該当オブジェクトに当たり判定用のコライダーは必要(ポイント)

・該当オブジェクトにTagの設定

・任意のオブジェクトにスクリプトを追加