LoginSignup
2
1

More than 5 years have passed since last update.

Unity + iOSで GameObjectのtouchの検出と関連処理の実行

Posted at

やりたかったこと
* iOSでsphere objectをタッチすると、そのsphereに割り当てられた情報を Canvasに出力する。

はまった点(伝わりづらくてすみません)
Raycast した結果、hitしたObjectの処理を実行する部分と、ローカルの関数が同じスクリプトなので、hitした Objectの関数を実行しないといけないところ、ローカルの関数を実行したことにより、対象のObjectの処理が実行できなかった.

下のEventScriptをSphereのコンポーネントとして追加して利用.

public class EventScript : MonoBehaviour {

    void Start () {
    }

    void Update () {
        if (Input.touchCount > 0){
            Touch _touch = Input.GetTouch(0);
            if(_touch.phase == TouchPhase.Began){
                Ray ray = Camera.main.ScreenPointToRay(_touch.position);
                RaycastHit hit = new RaycastHit();

                if (Physics.Raycast(ray, out hit)){

                    // タッチされたobjectの色を変える
                    hit.collider.GetComponent<MeshRenderer>().material.color = Color.red;

                    // タッチの対象をtargetタグを持つobjectに限る
                    if (hit.collider.transform.tag == "target") {
                        GameObject obj = hit.collider.gameObject;
                        Debug.Log(obj.name);

                        // Coroutineの実行
                        StartCoroutine(obj.GetComponentInParent<EventScript>().showInfoCanvas());
                    }
                }
            }
        }
    }

    IEnumerator showInfoCanvas(){
        // ...
        // WWW などを利用
    }
}

StartCoroutineの記述部分ではまった。localのshowInfoCanvasを実行していたら、他にも同じスクリプトが設定されているsphereのshowInfoCanvasも実行されてしまい、大量にイベントが発生する事態に...

結局は、タッチされたsphereの showInfoCanvasを実行するように記述したら上手く動いた.

// 上手く動かなった記述
StartCoroutine(showInfoCanvas()); // localのshowInfoCanvasを実行

// 正しい動き
StartCoroutine(obj.GetComponentInParent<EventScript>().showInfoCanvas()); // タッチされたobjectのshowInfoCanvasを実行

でも、そもそもタッチを検出するスクリプトと、イベントの内容が同じScript内にない方が良さそうだし、タッチ検出の処理は、どこかもっとグローバルなObject(カメラとか?)に設定して、検出処理を1回に止めた方が良さそう.
設定する対象を間違えている気がする...

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1