Search code examples
c#performanceunity-game-enginetreeenvironment

How to save and load environment in a survival type game?


I am working on a survival type game and in this game the entire map is manually made and split into multiple 512x512 size chunks/terrains. Depending on the player position chunks are loaded and unloaded.

The problem I am facing is saving and loading the chunk environment. In the game the player is able to chop down trees and also plant them back.

Considering that there's no knowing where and how many trees there will be in the chunk I can't use pool system and if I instantiate all the trees when I load up the chunk I could be calling thousands of instantiate calls, which would kill the performance.

How should I approach this, what could be a good solution for this? Thank you


Solution

  • Alright then, I just found a solution. The Addressables. Using Addressables.LoadAssetAsync and Addressables.InstantiateAsync.

    I made a simple test where I created 5000 complex meshes and got zero lag.. Quite unbelievable.

    This is the code, if anyone is interested.

    using System.Collections;
    using UnityEngine;
    using UnityEngine.AddressableAssets;
    using UnityEngine.ResourceManagement.AsyncOperations;
    
    using SystemRan = System.Random;
    
    public class Massinstantiation : MonoBehaviour
    {
        const string location = "Assets/TestObject.prefab";
    
        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.P))
            {
                StartCoroutine(Instantiate());
            }
        }
    
        public IEnumerator Instantiate()
        {
            var loadAsset = Addressables.LoadAssetAsync<GameObject>(location);
    
            yield return loadAsset;
    
            if (loadAsset.Status == AsyncOperationStatus.Succeeded)
            {
                SystemRan rand = new SystemRan();
                for (int i = 0; i < 5000; i++)
                {
                    var obj = Addressables.InstantiateAsync(location, new Vector3(rand.Next(-250, 250), 0, rand.Next(-250, 250)), Quaternion.identity, null);
                    yield return obj.IsDone;
                }
            }
        }
    }