Skip to content

Instantly share code, notes, and snippets.

@nevarman
Created February 12, 2019 12:09
Show Gist options
  • Save nevarman/1e81f0ec32b9c85d8988e769429a931c to your computer and use it in GitHub Desktop.
Save nevarman/1e81f0ec32b9c85d8988e769429a931c to your computer and use it in GitHub Desktop.
using UnityEngine;
using Unity.Entities;
using Unity.Entities.Serialization;
using Unity.Transforms;
using System.Threading.Tasks;
using Unity.Rendering;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class SerializeWorldTestCode : MonoBehaviour
{
[SerializeField]
GameObject spawnObjects;
[SerializeField]
GameObject sharedComponentsInObject;
public MeshInstanceRenderer[] renderers;
private World localWorld;
const string fileName = "savefile.sav";
private const string prefabPath = "Assets/Serialize/SharedComponents.prefab";
private void OnEnable()
{
localWorld = new World("local world");
localWorld.GetOrCreateManager<EntityManager>();
}
private void OnDisable()
{
localWorld.Dispose();
}
public void OnClickSerialize()
{
var eManager = World.Active.GetExistingManager<EntityManager>();
int[] sc;
using (var writer = new StreamBinaryWriter(fileName))
{
SerializeUtility.SerializeWorld(eManager, writer, out sc);
SerializeUtilityHybrid.Serialize(eManager, writer, out sharedComponentsInObject);
}
#if UNITY_EDITOR
PrefabUtility.CreatePrefab(prefabPath, sharedComponentsInObject);
EditorUtility.RevealInFinder(prefabPath);
#endif
}
public async void OnclickDeserialize()
{
var eManager = localWorld.GetExistingManager<EntityManager>();
var num = SerializeUtilityHybrid.DeserializeSharedComponents(eManager, sharedComponentsInObject, null);
var transaction = eManager.BeginExclusiveEntityTransaction();
await Task.Run(() =>
{
using (var reader = new StreamBinaryReader(fileName))
{
SerializeUtility.DeserializeWorld(transaction, reader, num);
}
SerializeUtilityHybrid.ReleaseSharedComponents(transaction, num);
});
eManager.EndExclusiveEntityTransaction();
World.Active.GetExistingManager<EntityManager>().MoveEntitiesFrom(eManager);
}
public void Spawn()
{
var random = new Unity.Mathematics.Random((uint)Time.frameCount);
var eManager = World.Active.GetExistingManager<EntityManager>();
for (int i = 0; i < 100; i++)
{
var entity1 = eManager.Instantiate(spawnObjects);
eManager.AddComponentData(entity1, new Position() { Value = random.NextFloat3(-1, 1) * 10 });
var r = Random.Range(0, renderers.Length);
eManager.AddSharedComponentData(entity1, renderers[r]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment