Unity GUIText on Collision c#

2.7k views Asked by At

I'm writing a 3D maze program in C# and I need to have UI Text display "You Win!" When the player reaches the end of the maze.

I have a trigger set up in Unity as a cube, named FinishLine, and I have the UI text named winText

I'm getting an error on this line..

GUI.Box(New rect (10,10,100,90), winText);

the error is "The best overloaded method matfch for unityengine.gui.box (unityEngine rect, string)' has some invalid arguments

I also have no idea what those numbers are (10,10,100,90), so maybe that's messing something up? What are those values indicating...?

Here is my code..

public class TextTrigger : MonoBehaviour {

     public GUIText winText;
     private bool FinishLine = false;

     void Start () {
         FinishLine = false;
     }

     void OnTriggerEnter(Collider col){
         if (col.tag == "Player") {
             FinishLine = true;   
         }
     }

     void OnGui() {
         GUI.Box(new Rect(10,10,100,90), winText);
     }
 }

EDIT - Updated my code, and I have a new error. On line 21 it says: "UnityEngine.Texture does not contain a definition for text and no extension method 'text' accepting a first argument of type 'UnityEngine.Texture' could be found. Are you missing a using directive or an assembly refrence?

NEW CODE:

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

public class FinishLine : MonoBehaviour {

public Texture winText;     private bool FinishPlane = false;

// Use this for initialization  void Start () {         FinishPlane =

false;

}

void OnTriggerEnter(Collider col)   {       if (col.tag == "Player") {
        FinishPlane = true;             winText.text = "You Win!";      }   } }
1

There are 1 answers

7
Programmer On BEST ANSWER

First of all, it is OnGUI not OnGui. The spelling counts. If you find yourself using OnGUI, stop and find other ways to accomplish whatever you are doing.

GUIText is a legacy UI Component. It's old and the Text component should now be used. If you still want to use it, below is the proper way to use GUIText.

public GUIText winText;
private bool FinishLine = false;

void Start()
{
    FinishLine = false;
}

void OnTriggerEnter(Collider col)
{
    if (col.tag == "Player")
    {
        FinishLine = true;
        winText.text = "You Win";
    }
}

Text component should be used for this and below is how to do that with the Text component:

public Text winText;
private bool FinishLine = false;

void Start()
{
    FinishLine = false;
}

void OnTriggerEnter(Collider col)
{
    if (col.tag == "Player")
    {
        FinishLine = true;
        winText.text = "You Win";
    }
}

You can learn more about Unity's new UI here.