user6160538
user6160538

Reputation: 97

Unity reticle as a pointer

I have a 3d Unity game with few 3d objects in worldspace. I have a reticle in cameraspace. When reticle crosses each 3d object, I have a pointer -enter and pointer-exit event written. when mobile phone is moved the reticle moves, but the 3d object stays in worldspace. The reticle is not functioning as pointer. Although the touch event is working, I could not make reticle as a pointer. I have added physics raycast with the camera. What mistake I am doing?

Upvotes: 2

Views: 3881

Answers (1)

Grant Mooney
Grant Mooney

Reputation: 390

Okay, so you are trying to use a UI.Selectable event (Selectable.OnPointerEnter) on a non-UI object.

Assuming you have the reticle position in screen space, I highly recommend using Physics.Raycast from the a script attached to the Camera object, though it could simply reference the camera instance instead. We can use this combined with a "hitObject" to trigger custom reticle enter/exit/hover events as seen below:

CameraPointer.cs:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Camera))]
public class CameraPointer : MonoBehaviour {
    private GameObject hitObject = null;
    private Vector3 reticlePosition = Vector3.zero;
    private Camera camera;

    void Awake() {
        camera = GetComponent<Camera>();
    }

    // Update is called once per frame
    void Update () {
        // TODO: Replace with reticle screen position
        reticlePosition = Input.mousePosition;

        // Raycast variables
        Ray ray = camera.ScreenPointToRay(reticlePosition); 
        RaycastHit hit;

        // Raycast
        if (Physics.Raycast(ray, out hit)) {
            if (hitObject != hit.transform.gameObject) {
                if (hitObject != null) {
                    hitObject.SendMessage("OnReticleExit"); // Trigger "OnReticleExit"
                }
                hitObject = hit.transform.gameObject;
                hitObject.SendMessage("OnReticleEnter"); // Trigger "OnReticleEnter"
            } else {
                hitObject.SendMessage("OnReticleHover"); // Trigger "OnReticleHover"
            }
        } else {
            if (hitObject != null) {
                hitObject.SendMessage("OnReticleExit"); // Trigger "OnReticleExit"
            }
            hitObject = null;
        }
    }
}

MyObject.cs:

using UnityEngine;
using System.Collections;

public class MyObject : MonoBehaviour
{
    // Custom reticle events
    void OnReticleEnter()
    {
        Debug.Log("Entering over " + this.name);
    }
    void OnReticleExit()
    {
        Debug.Log("Exiting over "+this.name);
    }
    void OnReticleHover()
    {
        Debug.Log("Hovering over "+this.name);
    }
}

Upvotes: 4

Related Questions