Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Gui text

Discussion in 'Scripting' started by Yourname, Apr 20, 2015.

  1. Yourname

    Yourname

    Joined:
    May 21, 2013
    Posts:
    15
    Does anyone know how to solve this problem?

    Assets/Scripts/CoinCounter.cs(12,25): error CS0120: An object reference is required to access non-static member `UnityEngine.GUIText.text'
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. public class CoinCounter : MonoBehaviour
    6. {
    7.     public int coinCount = 0;
    8.    
    9.     // Update is called once per frame
    10.     void Update ()
    11.     {
    12.         GUIText.text = "x" + coinCount;
    13.     }
    14. }
    I can't figure out why it is giving me this error.
     
  2. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,534
    GUIText is the name of a class, not a reference to an object.

    If you're using GUI Text, add a public variable:
    Code (csharp):
    1. public GUIText guiText;
    and assign it in the inspector. Then change the line to:
    Code (csharp):
    1. guiText.text = "x" + coinCount;
    If you're using the new Unity UI, use "Text" instead to refer to a Unity UI Text element.

    (If you don't want to assign it in the inspector, you may be able to use GetComponent<GUIText>().)
     
    Last edited: Apr 20, 2015
  3. Yourname

    Yourname

    Joined:
    May 21, 2013
    Posts:
    15
    Text is working, but there is a new issue:

    NullReferenceException: Object reference not set to an instance of an object
    CoinCounter.Update () (at Assets/Scripts/CoinCounter.cs:12)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. public class CoinCounter : MonoBehaviour
    6. {
    7.     public int coinCount = 0;
    8.     Text text;
    9.     // Update is called once per frame
    10.     void Update ()
    11.     {
    12.         text.text = "x" + coinCount;
    13.     }
    14. }
    15.  
     
  4. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    You should do the Unity tutorials before trying this. This is basic programming and is explained in detail in the tutorials.
     
  5. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,534