- Home /
unity2D touch drag
hi friends, I want to make a game in which I am instantiating many objects I want them to be able to move when the user touch and drag any of these. If user drags say sprite1 then only sprite1 should move, no else. I am using this code but when I run it on android application exits, it may have some errors. please help me to get a working script. `using UnityEngine; using System.Collections;
public class Text : MonoBehaviour { public float speed = 1F; void Update() { Vector2 rray = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); RaycastHit2D hit; if (Physics2D.Raycast (rray, Vector2.zero)) { if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved) { Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition; hit.transform.Translate (touchDeltaPosition.x speed, touchDeltaPosition.y speed, 0); } } } }`
You are using;
Input.GetTouch(0).position
...before you check if there are any touches. That is, this code will generate a null reference exception if touchCount == 0
Your answer
Follow this Question
Related Questions
Unity2D iOS Dragable items by touch 0 Answers
Dragging Camera based on Touch 0 Answers
Stretch sprite to a position (finger position) 1 Answer
Mobile touch dragging from mouse dragging 1 Answer
Drag object relative to camera 1 Answer