make water generation idempotent

This commit is contained in:
in0finite 2022-01-27 00:47:44 +01:00
parent ca5c801cec
commit 5761dae758
3 changed files with 33 additions and 2 deletions

View file

@ -1,5 +1,6 @@
using SanAndreasUnity.Importing.Items;
using SanAndreasUnity.Importing.Items.Placements;
using SanAndreasUnity.Utilities;
using System.Linq;
using UnityEngine;
@ -106,13 +107,25 @@ namespace SanAndreasUnity.Behaviours.World
mesh.normals = normals;
mesh.SetIndices(indices, MeshTopology.Triangles, 0);
var go = Instantiate(this.WaterPrefab, this.transform);
var availableObjects = this.transform.GetFirstLevelChildren().ToQueueWithCapacity(this.transform.childCount);
var go = availableObjects.Count > 0
? availableObjects.Dequeue().gameObject
: Instantiate(this.WaterPrefab, this.transform);
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = Quaternion.identity;
go.name = "Water mesh";
go.GetComponent<MeshFilter>().sharedMesh = mesh;
var meshFilter = go.GetComponentOrThrow<MeshFilter>();
if (meshFilter.sharedMesh != null)
F.DestroyEvenInEditMode(meshFilter.sharedMesh);
meshFilter.sharedMesh = mesh;
foreach (var availableObject in availableObjects)
F.DestroyEvenInEditMode(availableObject.gameObject);
}
void CreateQuad(Vector2 min, Vector2 max, Vector3[] vertexes, Vector3[] normals, ref int vertexIndex, int[] indexes, ref int indexesIndex)

View file

@ -22,5 +22,13 @@ namespace SanAndreasUnity.Utilities
{
return new Queue<T>(enumerable);
}
public static Queue<T> ToQueueWithCapacity<T>(this IEnumerable<T> enumerable, int capacity)
{
var queue = new Queue<T>(capacity);
foreach (var item in enumerable)
queue.Enqueue(item);
return queue;
}
}
}

View file

@ -286,6 +286,16 @@ namespace SanAndreasUnity.Utilities
}
}
public static List<Transform> GetFirstLevelChildrenPreallocated(this Transform tr)
{
var list = new List<Transform>(tr.childCount);
for (int i = 0; i < tr.childCount; i++)
{
list.Add(tr.GetChild(i));
}
return list;
}
public static IEnumerable<T> GetFirstLevelChildrenComponents<T>(this GameObject go) where T : Component
{
return go.transform.GetFirstLevelChildren().SelectMany(c => c.GetComponents<T>());