3Dゲームオブジェクトをマウスでクリックした時に処理をしたい
オブジェクトをクリックするとそのオブジェクトのComponentにアクセスできるようにします。
void Update()
{
// マウス左ボタンをクリックした時
if (Input.GetMouseButtonDown(0))
{
// スクリーン位置から3Dオブジェクトに対してRay(光線)を発射
Ray rayOrigin = Camera.main.ScreenPointToRay(Input.mousePosition);
// Rayがオブジェクトにヒットした場合
if (Physics.Raycast(rayOrigin, out RaycastHit hitInfo))
{
// タグがPlayerの場合(このif文を削除すると、全てのゲームオブジェクトに対する処理になります)
if (hitInfo.collider.CompareTag("Player"))
{
// ランダムな色に変更する場合
hitInfo.collider.GetComponent<MeshRenderer>().material.color =
new Color(Random.value, Random.value, Random.value);
}
}
}
}
usingを含めた全コード
using UnityEngine;
public class RayCastTest : MonoBehaviour
{
void Update()
{
// マウス左ボタンをクリックした時
if (Input.GetMouseButtonDown(0))
{
// スクリーン位置から3Dオブジェクトに対してRay(光線)を発射
Ray rayOrigin = Camera.main.ScreenPointToRay(Input.mousePosition);
// Rayがオブジェクトにヒットした場合
if (Physics.Raycast(rayOrigin, out RaycastHit hitInfo))
{
// タグがPlayerの場合(このif文を削除すると、全てのゲームオブジェクトに対する処理になります)
if (hitInfo.collider.CompareTag("Player"))
{
// ランダムな色に変更する場合
hitInfo.collider.GetComponent<MeshRenderer>().material.color =
new Color(Random.value, Random.value, Random.value);
}
}
}
}
}
訪問数 136 回, 今日の訪問数 1回

![Unity 6.6で[field: SerializeField]を付けたプロパティがインスペクタに表示される様子](https://soft-rime.com/wp-content/uploads/2026/09/unity6-property-inspector-hyoji-150x150.png)







ディスカッション
コメント一覧
まだ、コメントがありません