Unsure how to serialize MonoBehaviours and Scriptable Objects

Hi all,

I have made an AI system that uses both MonoBehaviours and Scriptable Objects and I need to sync information between the two. This results in having to pass the MonoBehaviour around or at least a Scriptable Object. I looked into the Serialization tutorial in Photon and I really didn't understand a whole lot, as usual. So I went to the internet and did some searching. Anyway here is my serialize/deserialize code:

public static class CustomPUNSerialization { public static byte[] SerializeGameObject(GameObject _obj) { BinaryFormatter b = new BinaryFormatter(); using (MemoryStream m = new MemoryStream()) { b.Serialize(m, _obj); return m.ToArray(); } } public static GameObject DeserializeGameObject(byte[] _array) { using (MemoryStream m = new MemoryStream()) { BinaryFormatter b = new BinaryFormatter(); m.Write(_array, 0, _array.Length); m.Seek(0, SeekOrigin.Begin); return (GameObject)b.Deserialize(m); } } public static byte[] SerializeEnemyAI(EnemyAI _ai) { BinaryFormatter b = new BinaryFormatter(); using (MemoryStream m = new MemoryStream()) { b.Serialize(m, _ai); return m.ToArray(); } } public static EnemyAI DeserializeEnemyAI(byte[] _array) { using (MemoryStream m = new MemoryStream()) { BinaryFormatter b = new BinaryFormatter(); m.Write(_array, 0, _array.Length); m.Seek(0, SeekOrigin.Begin); return (EnemyAI)b.Deserialize(m); } } }

I marked both classes EnemyAI and EnemyState with System.Serializable and ended up with an error that apparently MonoBehaviours and Scriptable Objects can't use the System.Serializable. So I am not sure exactly what to do at this point really. Any idea what can be done with this?

A sample of the code I have and will need to pass around in the network is this:

public void UpdateState(EnemyAI _ai) { if (PhotonNetwork.isMasterClient) { _ai.photonView.RPC("DoActions", PhotonTargets.All, CustomPUNSerialization.SerializeEnemyAI(_ai)); _ai.photonView.RPC("CheckState", PhotonTargets.All, CustomPUNSerialization.SerializeEnemyAI(_ai)); } } [PunRPC] private void DoActions(byte[] _ai) { EnemyAI ai = CustomPUNSerialization.DeserializeEnemyAI(_ai); for (int i = 0; i < actions.Length; i++) actions[i].ApplyAction(ai); } [PunRPC] private void CheckState(byte[] _ai) { EnemyAI ai = CustomPUNSerialization.DeserializeEnemyAI(_ai); ai.CheckState(decision.Decide(ai)); }
Sign In or Register to comment.