diff --git a/Assets/Scripts/Behaviours/World/Water.cs b/Assets/Scripts/Behaviours/World/Water.cs index ca299bc0..6c34ddf3 100644 --- a/Assets/Scripts/Behaviours/World/Water.cs +++ b/Assets/Scripts/Behaviours/World/Water.cs @@ -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().sharedMesh = mesh; + var meshFilter = go.GetComponentOrThrow(); + 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) diff --git a/Assets/Scripts/Utilities/CollectionExtensions.cs b/Assets/Scripts/Utilities/CollectionExtensions.cs index 3db20a18..9b35dbb1 100644 --- a/Assets/Scripts/Utilities/CollectionExtensions.cs +++ b/Assets/Scripts/Utilities/CollectionExtensions.cs @@ -22,5 +22,13 @@ namespace SanAndreasUnity.Utilities { return new Queue(enumerable); } + + public static Queue ToQueueWithCapacity(this IEnumerable enumerable, int capacity) + { + var queue = new Queue(capacity); + foreach (var item in enumerable) + queue.Enqueue(item); + return queue; + } } } diff --git a/Assets/Scripts/Utilities/F.cs b/Assets/Scripts/Utilities/F.cs index 571b4460..5b46ccbe 100644 --- a/Assets/Scripts/Utilities/F.cs +++ b/Assets/Scripts/Utilities/F.cs @@ -286,6 +286,16 @@ namespace SanAndreasUnity.Utilities } } + public static List GetFirstLevelChildrenPreallocated(this Transform tr) + { + var list = new List(tr.childCount); + for (int i = 0; i < tr.childCount; i++) + { + list.Add(tr.GetChild(i)); + } + return list; + } + public static IEnumerable GetFirstLevelChildrenComponents(this GameObject go) where T : Component { return go.transform.GetFirstLevelChildren().SelectMany(c => c.GetComponents());