- Home /
serialize static fields
I am trying to make a simple video game and I need to use the "static" keyword for some reason
static public int Level;
but when I do that it doesn't serialize a field for my variable. I tried to use this code but it didn't work (I looked at the scripting reference of unity after testing it. It also says SerializeField cannot serialize static fields. )
[SerializeField()]
static public int Level;
Is there any way to serialize a static field? Thanks for help from now.
Why would you want to serialize a static field? Do you want Level
to be accessible from other scripts? Then using static
is not advised because it's not the purpose of the static
modifier. Ins$$anonymous$$d, I advise you to keep Level
as a simple integer and use another way to access the variable. Either by using a direct reference to your script (and take advantage of the drag & drop system of the Unity inspector, or if you don't have this possibility, to use the Find
/ FindObjectOfType
functions), or by using the Singleton design pattern.
The problem is not about accessible. $$anonymous$$y game has multiple scenes and the player's level must be protected. When loading another scene.
Answer by PizzaPie · Sep 09, 2018 at 02:10 PM
You could create a helper field to store the value/ manipulate it in the editor and load it on Deserialization something like this.
public static int myStaticInt;
[SerializeField]
private int intSerializationHelper; //don't use for anything else
public void OnAfterDeserialize()
{
myStaticInt = intSerializationHelper;
}
public void OnBeforeSerialize()
{
//intSerializationHelper = myStaticInt; // uncomment this if you want the field to reflect the value of the static field on playmode
}
or probably better use another object (preferably a scriptable object to store the value), keep in mind that changes upon playmode will not remain after termination. This method is fairly unoptimized as it will perform the same action for every instance of said class. Don't forget to add the ISerializationCallbackReceiver interface on the class.
You could always hardcode the value.
Your answer
![](https://koobas.hobune.stream/wayback/20220612174309im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Using reflection, sometimes a field is "null" and sometimes it is "Null"? 3 Answers
How to serialized a variable in a c# method? 1 Answer
Insert enum breaking existing inspector values 2 Answers
Can a GameObject be serialized? 1 Answer
[HideInInspector] not serializing variables - how exactly does it work? 2 Answers