Home Unity

Gui text

Greg DAlessandro
polycounter lvl 6
Offline / Send Message
Greg DAlessandro polycounter lvl 6
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'
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class CoinCounter : MonoBehaviour 
{
	public int coinCount = 0;
	
	// Update is called once per frame
	void Update () 
	{
		GUIText.text = "x" + coinCount;
	}
}
I can't figure out why it is giving me this error.

Replies

  • Farfarer
    GUItext is just a class. You need to make an instance of the class before setting it's text.
    GUIText myText;
    myText.text = "my text here";
    

    Or it might be a mono behaviour so you'll have to add a GUIText component to your object and get a reference to it.
  • Greg DAlessandro
    Offline / Send Message
    Greg DAlessandro polycounter lvl 6
    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)
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class CoinCounter : MonoBehaviour
    {
        public int coinCount = 0;
        Text text;
        // Update is called once per frame
        void Update ()
        {
            text.text = "x" + coinCount;
        }
    }
    
  • SanderDL
    Offline / Send Message
    SanderDL polycounter lvl 7
    You are declaring your Text as a variable. But in C# variables are set to private by default. And you are not putting anything in, so it can't find anything in there and throws a NullReferenceException.

    What you could do is put public in front of your variable so it becomes visible in the inspector. Then just drag your UI text into it.
Sign In or Register to comment.