0

I am struggling with this problem for quite a while now: I have this static class:

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

namespace Platformer;
{
    public static class VarBoard
    {
        public static GameObject Player;
        public static GameObject LevelGenerator;
        public static GameObject PlayerHealthBar;
        public static List <GameObject> AllEnemies = new List<GameObject> ();
        public static List <GameObject> AllFriends = new List<GameObject> ();
    }
}

This class stores all global Variables, so I can use them from various places in my project, like this:

using UnityEngine;
using System.Collections;
using Platformer;

public class HealthBar : MonoBehaviour
{
    void Update{
        this.GetComponent<RectTransform> ().sizeDelta = new Vector2 (VarBoard.Player.GetComponent<Character> ().health, 40);
    }
}

I found this structure in this tutorial and it seemed to be a reasonable solution for me, but when I run the code I just get this

Exception: NullReferenceException: Object reference not set to an instance of an object

But as far as I understand, isn't it the purpose of a static class that you don't need instances of it? Or am I missing something here?

Steven
  • 166,672
  • 24
  • 332
  • 435
toddodd
  • 1
  • 2
  • Check this part of the code new Vector2 (VarBoard.Player.GetComponent ().health, 40); Player needs to be initialized before using it. – sszarek Apr 24 '15 at 10:03
  • 1
    Sriram, this isn't a duplicate of that, the op isn't asking how to fix the issue, but instead, do you need an instance for a static member – Sayse Apr 24 '15 at 10:04
  • 1
    The `VarBoard.Player` is null, you need to initialize`Player` – 3dd Apr 24 '15 at 10:08

2 Answers2

1

You need to initialise the static class object (the singleton) by way of its constructor.

public static class GameItemService
{
    // We don't have a database, just a singleton
    public static List<GameItem> LIST_OF_GAME_ITEMS; // A singleton for add/retrieve data


    static GameItemService()
    {
        LIST_OF_GAME_ITEMS= new List<GameItem>();
        // Add to the list here
    }

And then you can use the singleton e.g.

var items = GameItemService.LIST_OF_GAME_ITEMS.Take(20);

or similar.

Does that help?

VictorySaber
  • 3,084
  • 1
  • 27
  • 45
  • Not sure if "singleton" is the correct word here. A `static` property (or class) does not specifically have to be a singleton. I'd replace it with "property". Rest of the answer is correct though. – Dion V. Apr 24 '15 at 10:36
0

They still need to point to something in memory

As stated on MSDN

"Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object."

Sayse
  • 42,633
  • 14
  • 77
  • 146