- Home /
Can't access singleton's dictionary from another singleton
Edit: removed unrelated code.
Maybe someone could help, cause I'm out of clues what's happening. I have several singletons managing stuff like inventory, ui display, etc. I have specific class responsible for executing actions when you click on button, and one case is to look for key in dictionary. Function looks like this:
public bool EvaluateOne(ConditionTypes type, string value)
{
SafeDubug.Log("current items? " + InventoryManager.Instance.currentItems.Count); // shows like it is empty, but from within InventoryManager it is not?? wtf?
bool test = false;
switch (type)
{
case ConditionTypes.IsKeySet:
if (gameManager.keys.ContainsKey(value))
{
test = true;
}
break;
case ConditionTypes.HasItem:
if (InventoryManager.Instance.HasItem(value))
{
test = true;
}
break;
}
return test;
}
Inventory class looks like this:
public class InventoryManager : Singleton<InventoryManager>
{
public Dictionary<string, InventoryItem> currentItems = new Dictionary<string, InventoryItem>();
// removed code
public bool HasItem (string name)
{
return currentItems.ContainsKey(name);
}
// removed code
}
Base class is taken straigh from here: https://github.com/UnityCommunity/UnitySingleton/blob/master/Assets/Scripts/Singleton.cs
Generally, if I access dictionary from within InventoryManager, it's there, I can access entries, but from within another singleton, it looks like it's not there. I'm clueless.
can you do me a favour and remove all but the related code from your example please. Your Generic base class implementation may also be useful to see.
The SingletonT class you are extending isnt a singleton. (sorry that was supposed to be a comment.)
The very fact that its Generic makes it damn near impossible for it to be a singleton and there is nothing in it that guarantees that it's the only instance.
Try implementing your Inventory manager in the singleton pattern as outlined in one of these examples and the problem should hopefully disappear.
Thanks, I'll take a closer look at it. At least I know nw what can cause it.
Just did some reading and apparently using the new() type constraint opens up this pattern
public class Singleton<T> where T : class, new()
{
private Singleton (){}
private static readonly Lazy<T> instance = new Lazy<T>(()=> new T());
public static T Instance { get { return instance.Value; } }
}
I havent really had a good think about the problems you may face with this but at least this is an actual singleton:
Use
var journalSingleton = Singleton<JournalClass>.Instance;
And you get to keep the generic type.
reference
https://stackoverflow.com/questions/2319075/generic-singletont
Your answer
Follow this Question
Related Questions
Access Inventory from player 1 Answer
Item Database / Dictionary 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Accessing a Class's Variables from within a Dictionary Element 1 Answer