- Home /
An object reference is required to access non-static member
A lot of similar questions and answers but I can't make this work. This error keeps showing up no matter what:
"An object reference is required to access non-static member CoinsCounter.Coins"
I have a Class Named Collect, which contains a public variable called Coin, this variable increases by 1 every time the player collides with an object using this script.(I guess so far this works because I can see the print on my console).
Now, the problem is that I have a GuiText and I want to use it to count and see the number of coins that I am collecting on my HUD.
I created a Class called CoinsCounter, drag it to my GuiText and inside it I have this piece of code:
using UnityEngine; using System.Collections;
public class CoinCounter : MonoBehaviour {
// Update is called once per frame
void Update () {
guiText.text = Collect.Coin;
}
}
I just want the GuiText to change the "0" value to the number of coins I am picking up.
Any idea?
Thank you very much for your time !!!
Answer by HappyMoo · Jan 02, 2014 at 03:13 PM
Hi,
if you have your Collect class just for the purpose of counting the players coins and don't want to instatiate objects from it, you can mark everything in it static
static class Collect
{
public static int Coins
}
Then your CoinsCounter - I suggest CoinsUpdater - would look like this
public class CoinsUpdater : MonoBehaviour
{
void Update()
{
guiText.text = Collect.Coins;
}
}
To understand what static means, check out this video: http://www.youtube.com/watch?v=nraOAaYLdRQ
Answer by NADRAC · Jan 02, 2014 at 11:45 PM
Thank you very much HappyMoo!!
I tried that but now I am getting another error.
Static class Collect' cannot derive from type
HitTrigger'. Static classes must derive from object.
Thank you for the video link as well.
I am not very familiar with C# as you can see.
I see... I don't know why you have to derive from HitTrigger and if that's a bad design, but you can make the error message go away if you remove the "static" in front of the "class Collect"