Search Unity

[SOLVED] How to Change Text in C#?

Discussion in 'Scripting' started by ChrisIsAwesome, Jul 28, 2017.

  1. ChrisIsAwesome

    ChrisIsAwesome

    Joined:
    Mar 18, 2017
    Posts:
    184
    So I just made the leap from being a JS newbie to a true C# programmer, but I have one issue:

    How do I change UI text in C#?

    In JS, you'd make a variable of type UI.Text

    But apparently that doesn't work in C#?

    I get an error saying:

    "Error CS0246: The type or namespace name 'UI' could not be found. Are you missing an assembly reference?"

    I thought maybe to include "using UnityEngine.UI" but that didn't change things.

    I don't know what to do here. How do I make a UI.Text variable?

    Any help would be greatly appreciated!

    - Chris
     
  2. ChrisIsAwesome

    ChrisIsAwesome

    Joined:
    Mar 18, 2017
    Posts:
    184
    EDIT: Found the solution with a different Google search than what I tried before and got this. So as I thought, "using UnityEngine.UI;"I is required, but then the variable type is simply Text, not UI.Text.

    Hope this answer helps anyone who comes across this issue!
     
  3. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    You do need a using UnityEngine.UI; and then declare the text like

    Code (csharp):
    1. using UnityEngine.UI;
    2.  
    3. public class MyClass : MonoBehaviour
    4. {
    5.   public Text myText;
    6.  
    7.   public void setText(string newText)
    8.   {
    9.     myText.text = newText;
    10.   }
    11. }
    I strongly suggest you step over to https://unity3d.com/learn and jump through some c# based tutorials - they'll help out a lot.
     
    ChrisIsAwesome likes this.
  4. TSC

    TSC

    Joined:
    Oct 15, 2012
    Posts:
    271
    Code (CSharp):
    1.  
    2. start
    3. WhatYouWant = textGO.GetComponent<Text>();
    4.  
    5. public Text WhatYouWant;
    6.  
    7. public GameObject textGO;
    8.  
    9. textGo.text = WhatYouWant;
     
    ChrisIsAwesome likes this.
  5. ChrisIsAwesome

    ChrisIsAwesome

    Joined:
    Mar 18, 2017
    Posts:
    184
    Both of you replied right after I figured it out :) Ty for the help!
     
    TSC and larku like this.
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    For the record, you could also write out the fully qualified name, as in UnityEngine.UI.Text. It doesn't make much sense for UI, but I frequently use it when I just want to get a single type, and am not interested in the rest of the namespace.