I want to select an object on the scene touching it on the screen. I have made this code and it perfectly works on Unity player or when i compile the application for Windows. When i compile for WebGL i have strange behaviours (tested on Firefox/Chrome)
The error i get is that , if i keep my finger pressed on the object, i get multile continuous click instead of a single one even if i'm using TouchPhase.Began. Someone knows how to fix this problem? Is a known issue?
Here's my code
using UnityEngine;
using System.Collections.Generic;
using System.Xml.XPath;
using UnityEngine.UI;
public class RaycastObjHit : MonoBehaviour
{
private GameObject working_object;
private GameObject touchedObject;
void Update()
{
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began)
{
Ray ray = Camera.current.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
string ObjHitName = hit.transform.name;
Debug.Log(hit.transform.name);
if (hit.collider != null)
{
touchedObject = hit.transform.gameObject;
if (touchedObject.GetComponent<Renderer>().material.color != Color.red )
{
changeColor(touchedObject.transform.name, Color.red);
}else{
changeColor(touchedObject.transform.name, Color.green);
}
}
Debug.Log("Touched " + touchedObject.transform.name);
}
}
}
public void changeColor(string objId, Color color)
{
working_object = GameObject.Find(objId);
working_object.GetComponent<Renderer>().material.color = color;
}
}
If someone want to know how i "solved" the problem here's my code. Is a simple workaround that is using a boolean to control if i'm keep pressing the monitor during the same event. I repeat,is only a workaround to solve this "incompatibility" with WebGL
using UnityEngine;
using System.Collections.Generic;
using System.Xml.XPath;
using UnityEngine.UI;
public class RaycastObjHit : MonoBehaviour
{
private GameObject working_object;
private GameObject touchedObject;
private bool touchBegan = false;
void Update()
{
if (Input.touchCount == 1)
{
if (Input.GetTouch(0).phase == TouchPhase.Began && !touchBegan)
{
touchBegan = true;
Ray ray = Camera.current.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
string ObjHitName = hit.transform.name;
Debug.Log(hit.transform.name);
if (hit.collider != null)
{
touchedObject = hit.transform.gameObject;
if (touchedObject.GetComponent<Renderer>().material.color != Color.red)
{
changeColor(touchedObject.transform.name, Color.red);
}
else
{
changeColor(touchedObject.transform.name, Color.green);
}
}
Debug.Log("Touched " + touchedObject.transform.name);
}
} else if (Input.GetTouch(0).phase == TouchPhase.Ended && touchBegan){
touchBegan = false;
}
}
}
public void changeColor(string objId, Color color)
{
working_object = GameObject.Find(objId);
working_object.GetComponent<Renderer>().material.color = color;
}
}