5
7

More than 5 years have passed since last update.

Unity2Dメモ1 タッチ座標にあるオブジェクトに値を送る

Last updated at Posted at 2014-05-15

タッチ座標にあるオブジェクトに値を送る

TouchManager.cs
public class TouchManager : MonoBehaviour {
    Vector2 touchPoint;
    RaycastHit2D hit;
    Touch touch;
    string sendStr = "";

    void Update()
    {
        if (Input.touchCount > 0) // タッチが開始されたら
        {
            this.touch = Input.touches[0];

            // タッチ座標を変換
            this.touchPoint= Camera.main.ScreenToWorldPoint(this.touch.position);

            if (touch.phase == TouchPhase.Began)
            {
                // Raycast(光線の出る位置, 光線の向き)
                this.hit = Physics2D.Raycast(this.touchPoint, Vector2.zero);

                if (this.hit)
                {
                    // タッチ座標にあるオブジェクト
                    GameObject selectedObject = this.hit.collider.gameObject;
      
                    switch (selectedObject.tag) // オブジェクトのタグ
                    {
                        case "A": 
                            this.sendStr = "A";
                            selectedObject.SendMessage("MethodA", this.sendStr);
                            break;
                        case "B": 
                            this.sendStr = "B";
                            selectedObject.SendMessage("MethodB", this.sendStr);
                            break;
                        case "C": 
                            this.sendStr = "C";
                            selectedObject.SendMessage("MethodC", this.sendStr);
                            break;
                    }
                }
            }
        }
    }
} 
5
7
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
5
7