Selecting Objects

This page details how to enable users to select game objects in the scene with mouse or touch input when using the Leia plugin.

Sample Scene: Assets/Leia/Examples/WorldSpaceUI/SelectingObjects

To start, we need to raycast from the user's head position, given by:

//returns the position of the user's head in worldspace
leiaDisplay.HeadPosition

in the direction of the point on the screen where the user clicked or tapped, which is given by:

Mouse Input:

//returns the position of the users click in worldspace
leiaDisplay.ScreenToWorldPoint(Input.mousePosition)

Touch Input:

//returns the position of the users touch in worldspace
leiaDisplay.ScreenToWorldPoint(Input.GetTouch(0).position)

The example code below will print a debug of which object in the scene the user clicked on.

Example code:

using LeiaUnity;
using UnityEngine;

public class ObjectClicker : MonoBehaviour
{
    LeiaDisplay leiaDisplay;

    void Start()
    {
        leiaDisplay = FindObjectOfType<LeiaDisplay>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 worldPoint = leiaDisplay.ScreenToWorldPoint(Input.mousePosition);

            RaycastHit hit;

            Ray ray = new Ray(
                leiaDisplay.HeadPosition, 
                Vector3.Normalize(worldPoint - leiaDisplay.HeadPosition)
            );
        
            if (Physics.Raycast(ray, out hit, Mathf.Infinity))
            {
                Debug.Log("Clicked on "+ hit.transform.name);
            }
        }
    }
}

To use it, create an empty game object in the scene and attach this script to it.

You should now be able to click on objects in the scene and see the name of the clicked object printed in the Unity debug console window.

Last updated