Files
Emberwild/Assets/GAME/Script/Editor/WorldObjectIdAssigner.cs
T
2026-06-22 16:18:34 +02:00

50 lines
1.9 KiB
C#

using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using Ashwild.Network;
namespace Ashwild.EditorTools
{
/// <summary>
/// Editor tool that assigns a unique, stable id (>= 0) to every scene WorldObject in the open
/// scene — Pickables and Harvestables alike, in one shared sequence. The ids are baked into the
/// scene asset, so all clients load the exact same mapping (the scene is shared). Run after
/// scattering or whenever scene objects are added/removed.
/// </summary>
public static class WorldObjectIdAssigner
{
#region Menu
/// <summary>
/// Finds all WorldObjects in the open scene and assigns them sequential unique ids.
/// </summary>
[MenuItem("Tools/Ashwild/Assign World Object IDs")]
public static void Assign()
{
WorldObject[] objects = Object.FindObjectsByType<WorldObject>(FindObjectsInactive.Include, FindObjectsSortMode.None);
if (objects.Length == 0)
{
Debug.Log("[WorldObjectIdAssigner] No WorldObject found in the open scene.");
return;
}
// Deterministic order so re-runs are stable within an editor session.
System.Array.Sort(objects, (a, b) => a.GetInstanceID().CompareTo(b.GetInstanceID()));
int next = 0;
foreach (WorldObject obj in objects)
{
SerializedObject so = new SerializedObject(obj);
so.FindProperty("id").intValue = next++;
so.ApplyModifiedPropertiesWithoutUndo();
EditorUtility.SetDirty(obj);
}
EditorSceneManager.MarkSceneDirty(objects[0].gameObject.scene);
Debug.Log($"[WorldObjectIdAssigner] Assigned ids to {objects.Length} WorldObject(s) (pickables + harvestables). Save the scene to bake them.");
}
#endregion
}
}