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;
public Canvas myCanvas;
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;
}
}
s_awali
2
You code seems right, don’t know why this is called multiple times. Maybe try to change to FixedUpdate ?
Anyway, a workaround would be using a bool to only register the first touch:
public class RaycastObjHit : MonoBehaviour
{
private GameObject working_object;
private GameObject touchedObject;
private bool touchBegan = false;
public Canvas myCanvas;
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;
}
}
}
}
Tanx s_awali, your workaround works like a charm.
Do not know why Phase.Began do not work on my WebGL 