I am trying to create mobile input for my Unity game, but no matter what I try, nothing seems to work. I am using c# for all of the coding. When the main menu loads, I use the following function inside of a script inside of a sprite:
void OnMouseDown (){
SceneManager.LoadScene("gameScreen");
}
And this code works perfectly fine, it successfully loads the screen. My next problem is encountered when I want to get mobile touch input on the next scene.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MobileTouchInput : MonoBehaviour {
bool supportsMultiTouch;
// Use this for initialization
void Start () {
supportsMultiTouch = Input.multiTouchEnabled;
Debug.Log ("MultiTouchSupport: " + supportsMultiTouch);
}
// Update is called once per frame
void Update () {
int nbTouches = Input.touchCount;
if (nbTouches > 0) {
Debug.Log (nbTouches + " touch(es) detected");
for (int i = 0; i < nbTouches; i++) {
Touch touch = Input.GetTouch (i);
Debug.Log ("Touch Index " + touch.fingerId + " detected at position " + touch.position);
TouchPhase phase = touch.phase;
switch(phase)
{
case TouchPhase.Began:
Ray screenRay = Camera.main.ScreenPointToRay(touch.position);
RaycastHit hit;
if (Physics.Raycast(screenRay, out hit))
{
Debug.Log("User tapped on game object " + hit.collider.gameObject.name);
}
break;
}
}
}
}
This script is attached to a sprite which also has a 2D Physics Raycaster Script attached to it? I am not sure what it does but I read somewhere that I needed one. I tried the same code with a 2D physics bounding rectangle but that didn't work either :( Upon building the project and running it on an android device, an LGV10 to be exact, it would work with the OnMouseDown()
function, load the next scene, and then refuse to work at all with touches on the gameScreen scene. I know this because none of the Debug.Log
statements show up when I tap on the sprite that has a raycaster attached to it.
Any help would be greatly appreciated, I have been working on this bug for about 2 days and it is becoming quite frustrating to me.
EDIT:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class SpriteDetector : MonoBehaviour, IPointerDownHandler
{
void Start()
{
addPhysics2DRaycaster();
}
void addPhysics2DRaycaster()
{
Physics2DRaycaster physicsRaycaster = GameObject.FindObjectOfType<Physics2DRaycaster>();
if (physicsRaycaster == null)
{
Camera.main.gameObject.AddComponent<Physics2DRaycaster>();
}
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
}
//Implement Other Events from Method 1
}
Above is the code for the SpriteDetector class that you created.