- Home /
Showing text using raycast, Calling UI text with raycast
I tried so many ways and they didn't work too well. I'm new at coding and im trying to use a device to change scene and i want to show a text on the canvas when i look to the object (using raycast).
Pls help :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SelectionManager : MonoBehaviour
{
[SerializeField] private string selectableTag = "minigameDevice";
public Text InteractableText;
public void Update ()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 5))
var selection = hit.transform;
if (selection.CompareTag(selectableTag))
{
InteractableText.gameObject.SetActive(true);
}
if (Physics.Raycast(ray, out hit, 5) && (Input.GetKey(KeyCode.E)))
{
var selection = hit.transform;
if (selection.CompareTag(selectableTag))
{
SceneManager.LoadScene(0);
}
}
}
}
Answer by lvskiprof · Jul 14, 2021 at 06:19 PM
Your code is enabling the Text object, but it was never set to any string, so I wouldn't expect anything to appear. I am guessing you want it to say something like "Hit 'E' to exit", since you are looking for the E key.
You should probably also have a boolean that show you have the text enabled and put an else if on the first if statement, so that when the Raycast shows they are not looking at it any more and your boolean shows the test is being displayed, you disable it to hide it again.
Your answer
Follow this Question
Related Questions
UI Text showing weird string value? 1 Answer
Hiding the part of a UI text behind a 3D object 1 Answer
[4.6 - UI] Change text on button click via script 1 Answer
Drag object and position(snap) on another similar one using Raycasting? 0 Answers
What's an easy way to align a UI element with a Raycast? 0 Answers