Making text appear when a parameter is met.
I am currently working on an rpg styled game and I have created a basic script. Essentially when a player is near an object and they press E then it activates the script. However as a newbie I haven't worked with canvas and things like that. Could someone please give me some tips or advice on making a text appear above the object or maybe even a text box at the bottom of the players screen. using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour
{
bool callActive = false;
Vector3 playerPosition;
Vector3 NPC;
// Vector3 position1 = new Vector3(0, 0, 0);
//Vector3 position2 = new Vector3(0, 0, 0);
float totalDistance;
void Start() {
// playerPosition = gameObject.transform.position;
}
void Update() {
playerPosition = gameObject.transform.position;
NPC = GameObject.FindWithTag("Respawn").transform.position;
distanceCalculator();
callDistance();
}
public void distanceCalculator()
{
playerPosition = gameObject.transform.position;
totalDistance = Vector3.Distance(playerPosition, NPC);
}
public void callDistance()
{
if(totalDistance<2 && Input.GetKey(KeyCode.E))
{
Debug.Log(totalDistance);
callActive = true;
}
else if (totalDistance>2)
{
callActive = false;
}
if(callActive == true)
{
Debug.Log("live");
}
}
}
Also if you have any suggestions for my code in general please let me know.
Answer by wfreeman480 · Jan 03 at 12:51 AM
Update: Here is my code. I have a text labeled "Text" under my canvas but the issue is I am getting a null reference. Not sure why or how that works. using UnityEngine; using System.Collections; using UnityEngine.UI; public class ExampleClass : MonoBehaviour {
public Text tex;
bool callActive = false;
Vector3 playerPosition;
Vector3 NPC;
// Vector3 position1 = new Vector3(0, 0, 0);
//Vector3 position2 = new Vector3(0, 0, 0);
float totalDistance;
void Start()
{
tex.gameObject.SetActive(false);
}
void Update() {
playerPosition = gameObject.transform.position;
NPC = GameObject.FindWithTag("Respawn").transform.position;
distanceCalculator();
callDistance();
isActive();
}
public void distanceCalculator()
{
playerPosition = gameObject.transform.position;
totalDistance = Vector3.Distance(playerPosition, NPC);
}
public void callDistance()
{
if(totalDistance<2 && Input.GetKey(KeyCode.E))
{
tex.gameObject.SetActive(true);
Debug.Log(totalDistance);
callActive = true;
}
}
public void isActive()
{
if(totalDistance>3)
{
callActive = false;
tex.gameObject.SetActive(false);
}
}
}
Update: so I restarted unity and my game has zero issues. Hope this helps someone else out!
Your answer
![](https://koobas.hobune.stream/wayback/20220613051216im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Help me with text array. 1 Answer
How to set the position of these Texts ?? 0 Answers
On trigger show text 1 Answer