I've seen this question several times on the site, however most of the solutions seem to indicate that I should just make it an instance variable rather than a static one. However, the whole point of the Singleton pattern is this static object that's consistently referred to. Here are the links I have looked at:
Member cannot be accessed with an instance reference; qualify it with a type name
Member '<method>' cannot be accessed with an instance reference
This last link led me to the following:
What does the 'static' keyword do in a class?
And I feel I do understand this. The point of the Singleton is that all classes share this one instance so it feels perfect? I don't see the issue? It should be static
according to Singleton conventions and frankly logic.
I'm in unity and am trying to make an inventory system for a game some fellow students and I are trying to make. I have the InventoryUI set up, however I would like to build a static inventory that is ever-present in the game. The InventoryUI will draw the necessary data from this Singleton class.
In other words, the PlayerInventory will act as the backend for the InventoryUI. The PlayerInventory will be a Singleton and the InventoryUI will draw the necessary data from PlayerInventory
Here is the relevant code for my Singleton class:
public class PlayerInventory : MonoBehaviour
{
private static PlayerInventory instance;
private PlayerInventory() { }
public static PlayerInventory getInstance()
{
if (instance == null)
return instance = new PlayerInventory();
return instance;
}
}
Here is the relevant code for my InventoryUI class:
public class PlayerInventoryUI : MonoBehaviour
{
//Inventory Instance
static PlayerInventory inventory;
void Start()
{
inventory = inventory.getInstance();
//cannot be accessed with an instance reference Error occurs here.
}
}
If possible, could someone explain to me why this error occurs as well as a possible solution.