How to send a text variable from a script to a text object?

Hi,

I already tried a few codes but somehow it does not work. I have a a few boxes in scene and if the camera is looking at them, some text should be send to a gui text object. The raycast is working now and i can debug the name of the object, but not send it to the text object “infotext”. Can you tell me wich code i have to add here?

here my raycast code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class raycast_findTriggers : MonoBehaviour {

// Use this for initialization
void Start () {
	

}

// Update is called once per frame
void Update () {

    RaycastHit hit;

    if (Physics.Raycast(transform.position,transform.forward, out hit,100))
    {
        Debug.Log(hit.transform.name);
                 
       // HERE I WANT TO SEND THE NAME OF THE OBJECT TO THE TEXTOBJECT called infotext.

    }

}
}

Good day.

once you have a hit with a collider, you can find the name of the object, by:

string NameToUse = hit.collider.gameObject.name;

Now, you must understand, you are trying tho chaange a property called text from a component called Text (this Text component have other properties like color, font, etc…). This component Text is inside a GameObject, what I supose its called infotext.

So, only needs to acces the textbox called “infotext”, select its component Text and change its property text. You can acces it by different ways. Easy way is to make a public Text variable (which will be the Text component), and assign the textbox to this variable via inspector (this way, the variable will look for a TExt component inside the infotext object).

public Text TextBoxToUse;

or, by code look for a GameObject in the scene called “infotext”

Text TextBoxToUse = GameObject.Find("infotext").GetComponent<Text>();

Once you have linked your TextBox Text component, to this variable, you only need to change its property text:

TextBoxToUse.text = NameToUse;

And thats all!!

Of course, you can do it all in one line:

GameObject.Find("infotext").GetComponent<Text>().text = NameToUse;

But as you will discover, using the GameObject.Find() is not recommended, so it is very slow and affects the performance. for using it once, there is no problem, but it can not be the regular way you find objects.

Bye!! :smiley:

hey, thank you very much for your great help and detailed explanaitions. It works now!