- Home /
Can't get touch position in variable?
I am new in unity trying to get touch position but having error this line:
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
here is my code:
using UnityEngine;
using System.Collections;
public class enemy : MonoBehaviour {
// Update is called once per frame
void Update () {
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
Vector2 touchPos = new Vector2(wp.x, wp.y);
transform.position = touchPos;
}
}
Error: Index out of bounds.
if your problem solved by the answer just accept so that it can be useful for others too..
Answer by HarshadK · Aug 07, 2014 at 08:07 AM
Firstly check if there are any touches before you access the Touches array.
So the code becomes:
public class enemy : MonoBehaviour {
// Update is called once per frame
void Update () {
if(Input.touchCount > 0) {
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
Vector2 touchPos = new Vector2(wp.x, wp.y);
transform.position = touchPos;
}
}
}
Set position like this:
transform.position = new Vector3(touchPos.x, touchPos.y);
Touch events wont work in editor. You have to test them on device itself.
yeah i didnt know that... Thanks a lot... i already have done this... tested on device
Your answer
![](https://koobas.hobune.stream/wayback/20220613160036im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
OnPointerExit Issue w/ Radial Menu on Android 1 Answer
Move object by touch input 5 Answers
Moving an Object to the position of touch 1 Answer
how do i use touch.Position 1 Answer
touch position to world position 2D 2 Answers