「Unity/Csharp/オブジェクト操作」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→回転値取得) |
(→全オブジェクト取得) |
||
| 行61: | 行61: | ||
} | } | ||
</pre> | </pre> | ||
| + | 参考:http://buravo46.hatenablog.com/entry/2014/12/31/064658 | ||
| + | |||
==全ボタンオブジェクト取得== | ==全ボタンオブジェクト取得== | ||
<pre> | <pre> | ||
2020年11月5日 (木) 16:18時点における版
目次
オブジェクト取得
GameObject obj = transform.Find("mc1").gameObject;
Vector3 pos = obj.transform.position;
一つ上の階層を指定
GameObject obj = transform.Find ("../mc1").gameObject;
ルートからの階層で指定
GameObject obj = transform.Find ("/Canvas/mc1").gameObject;
子オブジェクト一覧を取得
GameObject canvasObj = GameObject.Find ("Canvas");
Component[] objList = canvasObj.GetComponentsInChildren (typeof(Component));
foreach (Component component in objList) {
// オブジェクト名がmc_~のときのみ表示
if (component.name.IndexOf ("mc_") > -1) {
Debug.Log (component.name);
}
}
x方向に移動
void Update () {
Vector3 pos = transform.position;
transform.position = new Vector3(pos.x + 0.01f, pos.y, pos.z);
}
オブジェクト非表示
GameObject gameObj = GameObject.Find ("mc1");
gameObj.SetActive (false);
注意:一度ActiveをfalseするとFindで再度検索できなくなるので透明にするとかx,yを画面外にするのがよいかも。それが使えなければ、一度gameObjをActiveをFalseする前にプロパティに保存しておくのが良い。
他にenabledやinteractableがある
参考:http://portaltan.hatenablog.com/entry/2016/05/24/144108
クリックしたオブジェクト名取得(2D版)
カメラオブジェクトに設置
void Update () {
if (Input.GetMouseButtonDown(0)) {
Vector2 tap = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Collider2D collition = Physics2D.OverlapPoint(tap);
if (collition) {
Debug.Log (collition.transform.gameObject.name);
}
}
}
回転値取得
GameObject.Find("/Canvas/hoge").transform.localEulerAngles.z;
全オブジェクト取得
foreach (GameObject obj in UnityEngine.Object.FindObjectsOfType(typeof(GameObject)))
{
// シーン上のオブジェクトのみ
if (obj.activeInHierarchy)
{
Debug.Log(obj.name);
}
}
参考:http://buravo46.hatenablog.com/entry/2014/12/31/064658
全ボタンオブジェクト取得
foreach (GameObject obj in UnityEngine.Object.FindObjectsOfType(typeof(GameObject)))
{
// シーン上のオブジェクトのみ
if (obj.activeInHierarchy)
{
Button button = obj.GetComponent<Button>();
if (button != null)
{
Debug.Log(obj.name);
}
}
}
