I hear people talking about serializing variables among things in their unity projects and quite don't understand it. I see them using
[SerializeField]
and don't know why or what it does.
I looked up the definition of data serialization: Serialization is the process of converting the state information of an object into a form that can be stored or transmitted.
During serialization, objects write their current state to temporary or persistent storage. Later, the object can be recreated by reading or deserializing the state of the object from the store.
Objects are created as the program runs, and then reclaimed when unreachable, with a short lifespan. But what if we want to store the contents of the object permanently?
Convert it into a sequence of bytes and save it on a storage medium. Then serialization is required. [SerializeField] is to force Unity to serialize a private field. This is an internal Unity serialization function. Sometimes we need to Serialize a private or protected attribute. In this case, the [SerializeField] attribute can be used.
The above is some information I found, I hope it is correct and can bring you some help
Say, you have a field _speed and you want to set it using inspector. It means we want it to be serialized - stored somewhere in a human-readable and flexible format(e.g. xml), not directly in code. So when you edit fields in inspector, you edit the serialized data. During compilation, it's being deserialized and assigned to a field. This is how serialization/desearialization works. It is used to store non-static or just big amounts of data. In case of Unity it is used to show you everything in inspector. Transform has position and scale variables serialized and you can edit them.
In Unity there are two common ways to make fields assignable in inspector: using public fields or using [SerializedField] attribute for private ones.
Making fields public just to edit them with inspector is bad practice. If you can edit field in inspector, it means every other component can too, which is insecure. There is no good architecture that allows such things. If you want other components to edit the field, make it a property or make a set method. If you just need to assign fields by hand, don't use public fields. Avoid them.
When you use the [SerializeField] attribute, you create a private field that is accessible to this component only and you can assign it in inspector at the same time. If you need other components to read it, you can make a public property without set (public float Speed => _speed;).
This all is not an obligatory usage. Just good practice.
Any values set in the Unity inspector for any public fields or private/protected fields that use the attribute [SerializeField] are saved with the current scene file.
If you open up a Unity.scene file you will find a hierarchy of data that matches the scene hierarchy along with lists of what script or component classes are attached to that game object and what the field values of those classes/components should be.
When loading a level in Unity, the scene file is deserialized meaning that a program walks the data structure creating game objects. It then creates component and script class instances attached to those components and initializes them with the serialized data in the scene file. After that you end up with a level more or less the same as it was when saved in the unity editor.
In addition to your own Monobehaviour scripts having this ability, all the default unity components work this way. Transform uses serialized Vector3s for position, rotation and scale. MeshFilter components serialize a reference to a mesh asset and the MeshRenderer component references Materials that are used by the GPU to draw the mesh etc etc.
In short, serialisation is a process by which computers transform data so that it can be written to a file (or sent across a network via a protocol stream) and then later transformed back into the original set of objects it was to begin with (or as close as matters).
Related
I'm working on an application in unity that solves chemical problems. I need to store information about each chemical element offline. For example: hydrogen [mass 1, group 1...], oxygen[mass 16, group 6...] and so on. What do I need to use?
The probably simplest solution would be to use a serialization library, like json .net, these can convert your objects to a serialized stream that can be saved to file. Attributes can typically be used to control how the object will be serialized.
The other major option is to use a database, either a stand-alone database like postgres, or a in-process database like sqlite. The later makes things like deployment easier, but introduces some limitations, like not supporting multiple concurrent applications. In either case you would typically use an "Object Relational Mapper" (ORM), like Entity Framework. This is able to convert your objects directly to database tables.
Files are typically simpler to use, and suitable if you want to store few,larger blobs of data that rarely change. Databases are more suitable if you have many more smaller objects that you want to search among, or when persisting data more frequently.
Note that this is general advice, Unity might have some built in persistence that might or might not be suitable for your particular case.
ScriptableObjects are a great fit for this situation:
[CreateAssetMenu]
public class Element : ScriptableObject
{
[SerializeField]
private int mass;
[SerializeField]
private int group;
public int Mass => mass;
public int Group => group;
}
You can create an asset to hold information about each element.
Create scriptable object:
Add it from menu:
Set Desired data to element:
I Mean those fields.
[SerializeField]
public Type gameStateType;
[SerializeField]
public IGameStateParams gameStateParams;
I made in Editor methods to set those fields up, but, when click Play they go null.
I can deal with Type(all supported by my system types stored in dictionary, so i can just use their ID to get Type), but not with IWhatever implemented instance.
Can it be solved?
If not, is there any way to store in scene game object any IWhatever implemented instance?
These types (Type and interfaces) are not serializable .. so while you can of course use editor scripts to pass in values these fields will not be serialized => not saved => Not be initialized on runtime.
When you enter PlayMode all objects in the scene are reloaded => deserialized from scratch => since your values were never serialized they are also not deserialized.
See Script Serialization -> Serialization Rules
I'm working a game in Unity and I've got a Script where I save a lot of values in multiple variables, which I then use in other scripts. You could say its my GameState. The Script itself is not a GameObject, it purely exists to save values. When I start my game the "GameState" has some basic values like Name, TeamName, Money and tons of more variables which are static and filled with pre-set values.
Now comes my problem. If the player plays through the game and picks some options, functions get triggered which change the values in the GameState, like for example he'll receive more money, so the value for money in the GameState changes. But the player also has the option to completely "restart" the game by going back to the main menu (where I use a LoadScene Function). Problem is that the values in the GameState remain changed when he goes back, so when he starts a new game, he doesn't got the pre-set values, but the ones from his last game.
So my question would be, is there an easy way to reset my GameState completely to its original values? I know I could save the default values somewhere and then make a check to see if the game is reloaded to then use them, but I've already got like 60-70 variables in there and don't really want to create another 60-70 just for the default values (unless there is no other option). So does anyone have an idea how I could do that?
I don't think showing the code of the GameState does much, since its really just looking like:
public class GameState
{
//Team
public int TeamID;
public string TeamName;
public string TeamColor;
etc...
}
GameState is a class to contain data. An easy way to create default is to serialize it : add [System.Serializable] on top of the class declaration.
Now you can have say an object in your main scene called default values which has a public/serialized field of type GameState. You can set those in the editor save the scene and bam. Now to reset all the values to default you just copy the default to the current/active set of data.
If you want to expand a bit on that you can also turn the class into a scriptableObject but I don't think you need that.
I'm trying to synchronize a canvas with photon engine so every player can see it. This canvas will be kind of a tv that any player can turn on and the rest can watch it. I could synchronized a cube adding the PhotonView and the PhotonRigidBody components to the prefab but when I tried the same with the canvas it didn't work at all.
Can anyone tell me what components are required to do this and if it needed it what should I handle with an extra script (i.e transfer ownership).
There is nothing special about the canvas, but it could be locked in place.
There are two solutions I have for you:
Observable Component:
You could write a custom observable component, and add it to the PhotonView:
To make use of this function, the script has to implement the IPunObservable interface.
public class CustomObservable : MonoBehaviourPunCallbacks, IPunObservable
{
[SerializeField] PlayerController playerController;
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
stream.SendNext(playerController.playerNumber);
stream.SendNext(playerController.playerScore);
}
else
{
playerController.playerNumber = (int)stream.ReceiveNext();
playerController.playerScore = (float)stream.ReceiveNext();
}
}
}
Custom Properties:
You could also use custom properties to sync the data across all players.
Photon's Custom Properties consist of a key-values Hashtable which you can fill on demand. The values are synced and cached on the clients, so you don't have to fetch them before use. Changes are pushed to the others by SetCustomProperties().
How is this useful? Typically, rooms and players have some attributes that are not related to a GameObject: The current map or the color of a player's character (think: 2d jump and run). Those can be sent via Object Synchronization or RPC, but it is often more convenient to use Custom Properties.
PhotonNetwork.CurrentRoom.SetCustomProperties(Hashtable propsToSet)
You can write a script that uses Photons callback, and updated the UI elements.
OnRoomPropertiesUpdate(Hashtable propertiesThatChanged)
I am using factories to generate Objects, however I am having trouble figuring out how to add these created object instances to the unity scene.
If I add a component of the type, it's a new instance and doesn't have the created data.
If I try and instantiate, It won't work because it's a custom class and has no gameObject.
Is there a common way to do this? or do I have to redesign how this is working?
So far the only thing I can think of is creating an Initialize method in the objects that sets all the properties, and then after the object is created and generated, I create a new Component, and call the initialize method on the GetComponent that I just added, setting the values to the values from the generated object.
Seems like a headache and bad way to do it though.
Basically I'm generating Items, using some Randomization functions to get their rarity/itemType etc, and then creating said Item using factories as I won't know what type they are until the game is already running.
I'm, in theory, trying to generate everything without any need for a database, except a sprite > object connection. But, the more and more I get into this the more I think i'm going to have to have some sort of database.
Long story short, I need the instances in the Unity scene so that when a player clicks on them he can "equip them, disenchant them, etc"