3Dゲームオブジェクトをマウスでクリックした時に処理をしたい
オブジェクトをクリックするとそのオブジェクトのComponentにアクセスできるようにします。
void Update()
{
// マウス左ボタンをクリックした時
if (Input.GetMouseButtonDown(0))
{
// スクリーン位置から3Dオブジェクトに対してRay(光線)を発射
Ray rayOrigine = Camera.main.ScreenPointToRay(Input.mousePosition);
// Rayがオブジェクトにヒットした場合
if (Physics.Raycast(rayOrigine, out RaycastHit hitInfo))
{
// タグがCubeの場合(このif文を削除すると、全てのゲームオブジェクトに対する処理になります)
if (hitInfo.collider.CompareTag("Cube"))
{
// ランダムな色に変更する場合
hitInfo.collider.GetComponent<MeshRenderer>().material.color =
new Color(Random.value, Random.value, Random.value);
}
}
}
}
ディスカッション
コメント一覧
まだ、コメントがありません