facebook twitter hatena line email

Unity/Csharp/オブジェクト操作

提供: 初心者エンジニアの簡易メモ
2017年9月27日 (水) 02:55時点におけるAdmin (トーク | 投稿記録)による版

移動: 案内検索

x方向に移動

void Update () {
  Vector3 pos = transform.position;
  transform.position = new Vector3(pos.x + 0.01f, pos.y, pos.z);
}

オブジェクト取得

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);
    }
}

オブジェクト非表示

obj.SetActive (false);

クリックしたオブジェクト名取得(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);
		}
	}
}