Display Text on Object Touch in Unity

Welcome to this Unity tutorial, where you'll learn how to make text appear when touching an object in your game. This simple interaction can add an immersive element to your project. This tutorial will work on both mobile and desktop.

Step 1: Create a Unity Project

If you haven't yet, begin by opening Unity and creating a new 3D project. Ensure you have the necessary assets installed for your preferred development environment.

Step 2: Import 3D Object

Import a 3D object into your scene that represents the item players will interact with. This could be a cube, sphere, or any other object suitable for your game.

Step 3: Add Collider

Attach a collider component to your 3D object. This will enable it to detect when other objects interact with it. Common collider types include Box Collider, Sphere Collider, or Mesh Collider, depending on your object's shape.

Step 4: Create Canvas and Text

Create a UI Canvas by right-clicking in the scene hierarchy, selecting UI, and then Canvas. Inside the canvas, add a Text component that will display your message.

Step 5: Set Canvas to World Space

Change the Render Mode of the Canvas component to 'World Space'. This allows the canvas to exist in the 3D space of your game.

Step 6: Position Canvas

Adjust the position of the canvas so that it aligns with your 3D object. This ensures that the text appears near the object when triggered.

Step 7: Write Script

Write a script that will detect when the player interacts with the object. When interaction occurs, activate the Canvas and set the Text component's content. Check the example script below:

'ObjectInteraction.cs'

using UnityEngine;
using UnityEngine.UI;

public class ObjectInteraction : MonoBehaviour
{
    public GameObject canvas;
    public Text displayText;

    private void Start()
    {
        canvas.SetActive(false);
    }

    private void Update()
    {
        // Use inline conditional to determine input position based on platform
        Vector3 inputPosition = (Input.touchCount > 0) ? Input.GetTouch(0).position : (Vector3)Input.mousePosition;

        // Raycast to determine if the touch or click hits the object
        Ray ray = Camera.main.ScreenPointToRay(inputPosition);

        RaycastHit hit;
        if (Physics.Raycast(ray, out hit) && hit.collider.gameObject == gameObject)
        {
            // Activate the canvas and set the text
            canvas.SetActive(true);
            displayText.text = "Your message here!";
        }
    }
}

Step 8: Add Script to Object

Attach a C# script to your 3D object, that will handle the interaction logic and assign all the necessary variables.

Step 9: Test Your Game

Run your game and test the interaction. The text should appear when you click or touch the designated object.

Links
Unity 6