- Home /
Best way to serialize a ScriptableObject reference using NetworkWriter/Reader
It's easily possible to send GameObject references in the new networking system, but is there a similarily easy way to send references to ScriptableObjects?
We are using custom NetworkMessages, and the NetworkWriter doesn't seem to have an appropriate overload for this.
Our ScriptableObject references are always referencing asset files, so it doesn't need to work with dynamically created ScriptableObject instances.
Answer by ttRevan · Oct 30, 2015 at 07:31 PM
Not sure about build-in solution, but we using the code below for serializing gameObject prefabs (little more complicated though), it also works for ScriptableObjects:
public class SomeScriptableObject : ScriptableObject, ISerializationCallbackReceiver {
[SerializeField]
string id;
public string Id {
get { return id; }
}
public void OnBeforeSerialize() {
SetupGuid();
}
public void OnAfterDeserialize() {}
#if UNITY_EDITOR
void OnValidate() {
SetupGuid();
}
void SetupGuid() {
if (Application.isPlaying) {
return;
}
var assetPath = AssetDatabase.GetAssetPath(this);
id = AssetDatabase.AssetPathToGUID(assetPath);
}
#else
void SetupGuid() {}
#endif
}
What it does is saving asset id during Edit time in a string. you can send this string to another peer and lookup your SerializedObject by it. Of course, both peers must be built from the same project for their assets ids to match.
I don't know, but assume that Unity is doing something similar in its new NetworkIdentity.
Your answer
![](https://koobas.hobune.stream/wayback/20220612042418im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to add Multipeer support between iOS and Windows? 0 Answers
How to NetworkSerialize an Array? Always getting non-nullable Error 0 Answers
Unity Networking multiplayer 1 Answer
UNet - Connecting and Testing a 'choose your character' scenario 0 Answers
How do I save scripts as variables in the inspector? 0 Answers