I want to instantiate object to screen where I touch. I’m testing this on the android, but it doesn’t instantiate anything. Here is the code:
using UnityEngine;
using System.Collections;
using System;
public class TouchInputController : MonoBehaviour {
public bool showDebug = true; // if true
public GameObject particle;
private Vector3 _touchLocation;
private String _touchState;
private Vector3 _rayPosition;
private String _error;
// Update is called once per frame
void Update () {
if(Input.touchCount >= 1) {
_touchState = Input.GetTouch(0).phase.ToString();
_touchLocation = Input.GetTouch(0).position;
Ray ray = Camera.main.ScreenPointToRay(_touchLocation);
_rayPosition = ray.origin;
_rayPosition.z = 0;
try{
Instantiate(particle, _rayPosition, Quaternion.Euler(new Vector3(0.5f, 0.5f,0.0f)));
_error = "None";
}
catch(Exception e) {
_error = e.ToString();
}
}
else
_touchState = "None";
}
void OnGUI()
{
if (!showDebug)
return;
int fontSize = 20;
float guiWidth = Screen.width * 0.4f;
float guiHeight = 300;
float guiPoxX = Screen.width * 0.01f;
float guiPoxY = Screen.height * 0.03f;
float t_itemHeight = fontSize * 1.5f;
float t_itemY = guiPoxY + 5.0f;
float t_itemX = guiPoxX + 5.0f;
GUI.skin.label.fontSize = fontSize;
// Make a background box,
// static void Box(Rect position, string text);
GUI.Box(new Rect(guiPoxX, guiPoxY, guiWidth, guiHeight), "");
// get the number of boxes to spawn
GUI.Label(new Rect(t_itemX, t_itemY, guiWidth, t_itemHeight),
String.Format("touch count: {0}", Input.touchCount));
t_itemY += t_itemHeight;
// get the number of boxes to spawn
GUI.Label(new Rect(t_itemX, t_itemY, guiWidth, t_itemHeight),
String.Format("Touch Location: x:{0} y:{1}", _touchLocation.x, _touchLocation.y));
t_itemY += t_itemHeight;
// get the number of boxes to spawn
GUI.Label(new Rect(t_itemX, t_itemY, guiWidth, t_itemHeight),
String.Format("touch phase: {0}", _touchState));
t_itemY += t_itemHeight;
// get the number of boxes to spawn
GUI.Label(new Rect(t_itemX, t_itemY, guiWidth, t_itemHeight),
String.Format("Ray Location: x:{0} y:{1}", _rayPosition.x, _rayPosition.y));
t_itemY += t_itemHeight;
// get the number of boxes to spawn
GUI.Label(new Rect(t_itemX, t_itemY, guiWidth, t_itemHeight),
String.Format("Errors: {0}", _error));
t_itemY += t_itemHeight;
}
}