Search code examples
user-interfaceunity-game-enginevirtual-reality

Displaying a text when looking on a GameObject in Unity VR


I am trying to use Google VR asset for unity and it is pretty easy, I have already built the most of the things in my project.

I have just one issue, I don't find a way to display text to the player...

In my project the user walks around a model, and when he looks on a specific part of it, a window with the proper information pops up.

I have tried using OnGui function, but for no avail...

Do you have any idea how to do that?


Solution

  • You have to use a world-space canvas or a 3D Text. You will probably also want some billboarding (the text facing the user).

    I often use this helper for this (just drag to a new gameobject):

    using UnityEngine;
    
    [RequireComponent(typeof(TextMesh))]
    [RequireComponent(typeof(MeshRenderer))]
    [ExecuteInEditMode]
    public class Billboarded3dText : MonoBehaviour {
    
        public bool yawOnly = false;
        public float minimalViewDistance = 0.5f;
    
        private MeshRenderer meshRenderer;
        private TextMesh textMesh;
    
    
        private void OnEnable()
        {
            meshRenderer = GetComponent<MeshRenderer>();
            textMesh = GetComponent<TextMesh>();
        }
    
    
        private void LateUpdate()
        {
            var cam = Camera.main;
            if (cam == null) return;
    
            var lookDir = transform.position - cam.transform.position;
            if (yawOnly) lookDir.y = 0;
    
            if(Vector3.SqrMagnitude(lookDir) < minimalViewDistance)
            {
                meshRenderer.enabled = false;
            }
            else
            {
                meshRenderer.enabled = true;
                transform.rotation = Quaternion.LookRotation(lookDir);
            }
        }
    
    
    }