I have to load/unload models from a specific url based on player position. For this reason I am checking player position from model and then load/unload related piece of model in a Update event which runs on every frame.
Here is the update, that validating some checks before loading/unloading. I added this check for optimization purposes as the main loading/unloading loop is heavy:
private void Update() { //If this feature is disable don't load/unload if (enableThisFeature == false) return; //if player is moving, dont load//unload if (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0) { //do nothing when player is moving return; } DeactivateDistantTiles(); }
After this I am checking player postion and calling model load/unload:
private void DeactivateDistantTiles() { playerPosition = transform.position; playerPosition = cameraController.currentActiveCam.transform.position; //transform.position; checkPlayerPositionChangeing = playerPosition.z != playerLastPos.z || playerPosition.x != playerLastPos.x; if (checkPlayerPositionChangeing) { ABLoadUnloadLoopCall(); } playerLastPos = cameraController.currentActiveCam.transform.position; } Vector3 tilePosition; float xDistance; float zDistance; public void ABLoadUnloadLoopCall() { //old //foreach (SingleABLoader tile in tiles) //{ // Debug.Log("ABLoadUnloadLoopCall 123"); // Vector3 tilePosition = tile.gameObject.transform.position + (tileSize / 2f); // float xDistance = Mathf.Abs(tilePosition.x - playerPosition.x); // float zDistance = Mathf.Abs(tilePosition.z - playerPosition.z); // if (xDistance + zDistance > maxDistance) // { // /*If you don't want to destroy the object on unload then use below line otherwise use DestroyBundleObject with true pararmeter */ // //tile.DestroyBundleObject(); // tile.DestroyBundleObject(true); // } // else // { // tile.StartDownloadingAB(); // } //} //new for(int i = 0; i < tiles.Length; i++) { tilePosition = tiles[i].gameObject.transform.position + (tileSize / 2f); xDistance = Mathf.Abs(tilePosition.x - playerPosition.x); zDistance = Mathf.Abs(tilePosition.z - playerPosition.z); if (xDistance + zDistance > maxDistance) { /*If you don't want to destroy the object on unload then use below line otherwise use DestroyBundleObject with true pararmeter */ //tiles[i].DestroyBundleObject(); tiles[i].DestroyBundleObject(true); } else { tiles[i].StartDownloadingAB(); } } }
I found that ABLoadUnloadLoopCall
making GC allocation in KBs which is very high. So is there any way available that my above code optimize and make less allocation. My initial research suggest to use For loop instead foreach therefore in ABLoadUnloadLoopCall
i am using for loop instead foreach but still my game lag/freeze for some minutes after loading the model.