- Home /
Trouble with a static variable in a generic class
Hey folks, I've got a question about generic inheritance, and possibly static variables. I'm making a Pictionary game, and I'm saving how many times the game has been finished.
So I have a PictionarySaveManager
that inherits SaveManager<T>
. (I have a bunch of other games too, so that's why I'm using inheritance.) I also have a class for the save data, PictionarySaveData
. This class will plug into the generic class.
SaveData
is a public static variable of type T
. It's declared in the generic class and set in the child class. SaveData
is accessible in PictionarySaveManager
(where SaveData
is created and set), but it's not accessible in PictionarySaveManager
's parent, SaveManager<T>
. Since SaveData
is static, shouldn't it be accessible in both classes?
From what I understand, each type that's plugged into a generic class has its own class and would have its own static variable. link
A static variable in a generic class declaration is shared amongst all instances of the same closed constructed type (§26.5.2), but is not shared amongst instances of different closed constructed types. These rules apply regardless of whether the type of the static variable involves any type parameters or not.
Here's my data class:
[System.Serializable]
public class PictionarySaveData
{
public PictionarySaveData()
{
numOfGamesPlayed = 0;
}
public int numOfGamesPlayed;
}
Here's the generic class:
public class SaveManager<T> : MonoBehaviour {
public static T SaveData;
public void Save() {
...
/// SaveData isn't accessible in the generic parent class
bf.Serialize(file, (T)SaveData);
...
}
And here's the class that inherits the generic class:
public class PictionarySaveManager : SaveManager<PictionarySaveData> {
public static void GameFinished()
{
// SaveData is accessible in the inherited class
SaveData.numOfGamesPlayed++;
}
I'm new to generics so your help is appreciated! Thank you!