画面に表示されているオブジェクトにマウスを当てると、オブジェクトの色が変わるスクリプトを作ってみた
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class RayCast : MonoBehaviour { | |
void Start() { | |
} | |
void Update() { | |
//カメラ上にあるマウスの位置に飛ばすレイを作成する | |
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); | |
//レイがコライダーに当たった場合に情報を格納する | |
RaycastHit hit = new RaycastHit(); | |
//作成したレイを投げる。コライダーに当たった場合はtrueが返る | |
if (Physics.Raycast(ray, out hit)) | |
{ | |
//レイが当たったオブジェクトがChangeColorコンポーネントをアタッチしていた場合、フラグをtrueにする | |
if ( hit.collider.gameObject.GetComponent<ChangeColor>() ) { | |
hit.collider.gameObject.GetComponent<ChangeColor>().select_flg = true; | |
} | |
} | |
} | |
} |
マウス位置のレイを投げるスクリプト(RayCast.cs)を空のGameObjectにアタッチする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class ChangeColor : MonoBehaviour { | |
//選択判別用フラグ | |
public bool select_flg; | |
//選択時の色変更用 | |
private Color default_color; | |
private Color select_color; | |
//色変更対象のオブジェクトのマテリアル格納用 | |
protected Material mat; | |
void Start () { | |
//フラグ、色、マテリアルの初期化 | |
select_flg = false; | |
default_color = Color.gray; | |
select_color = Color.red; | |
mat = this.gameObject.GetComponent<Renderer>().material; | |
} | |
void Update () { | |
mat.color = default_color; | |
//フラグがtrueの場合(RayCast.csで変更される) | |
if (select_flg) { | |
//選択から外れたとき用 | |
select_flg = false; | |
//オブジェクトの色を変更する | |
mat.color = select_color; | |
} | |
} | |
} |
オブジェクトの色を変更するスクリプト(ChangeColor.cs)を対象のオブジェクトにアタッチする(ここではCubeのPrefab)