InvalidOperationException: You are trying to read Input using the UnityEngine.Input…
- User
InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings. UnityEngine.Input.GetKey (UnityEngine.KeyCode key) (at :0) Fabgrid.Brush.EvaluatePreConditions (UnityEngine.Event e) (at Assets/Fabgrid/Scripts/Editor/Tools/Brush.cs:41) Fabgrid.Brush.OnMouseDown (UnityEngine.Event e) (at Assets/Fabgrid/Scripts/Editor/Tools/Brush.cs:29) Fabgrid.Paint.OnMouseDown (UnityEngine.Event e) (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:602) Fabgrid.EventHandler.ProcessEvents (UnityEngine.Event e, Fabgrid.Tool currentTool) (at Assets/Fabgrid/Scripts/Editor/EventHandler.cs:38) Fabgrid.Paint.OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:294) Fabgrid.FSM.OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/FSM.cs:19) Fabgrid.Tilemap3DEditor.OnDuringSceneGUI (UnityEditor.SceneView sceneView) (at Assets/Fabgrid/Scripts/Editor/Tilemap3DEditor.cs:139) UnityEditor.SceneView.CallOnSceneGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEditor.SceneView.HandleSelectionAndOnSceneGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEditor.SceneView.DoOnGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEditor.SceneView.OnSceneGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, UnityEngine.Matrix4x4 worldTransform, UnityEngine.Rect clippingRect, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.SendEventToIMGUIRaw (UnityEngine.UIElements.EventBase evt, System.Boolean canAffectFocus, System.Boolean verifyBounds) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.SendEventToIMGUI (UnityEngine.UIElements.EventBase evt, System.Boolean canAffectFocus, System.Boolean verifyBounds) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.ProcessEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.CallbackEventHandler.HandleEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.CallbackEventHandler.HandleEventAtCurrentTargetAndPhase (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.CallbackEventHandler.UnityEngine.UIElements.IEventHandler.HandleEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatchUtilities.HandleEventAcrossPropagationPath (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatchUtilities.PropagateEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.MouseEventDispatchingStrategy.SendEventToRegularTarget (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.BaseVisualElementPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.MouseEventDispatchingStrategy.SendEventToTarget (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.BaseVisualElementPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.MouseEventDispatchingStrategy.DispatchEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel iPanel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ApplyDispatchingStrategies (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel, System.Boolean imguiEventIsInitiallyUsed) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ProcessEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ProcessEventQueue () (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.OpenGate () (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcherGate.Dispose () (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ProcessEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.Dispatch (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel, UnityEngine.UIElements.DispatchMode dispatchMode) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.BaseVisualElementPanel.SendEvent (UnityEngine.UIElements.EventBase e, UnityEngine.UIElements.DispatchMode dispatchMode) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& eventHandled) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIEventRegistration.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIEventRegistration+<>c.<.cctor>b__1_2 (System.Int32 i, System.IntPtr ptr) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& result) (at <9c5fbd2c5ba0433bb47ffef5ab9945cd>:0)
- Assistant
The error message:
InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.happens because your Unity project is set to use the new Input System (via Player Settings), but your code still tries to use the legacy Input API (
UnityEngine.Input), such asInput.GetKey(). This isn't allowed when the project uses the new Input System as the active input handling.
How to fix the error
You have a few options:
Option 1: Switch Player Settings back to the old Input System
Go to:
Edit → Project Settings → Player → Other Settings → Active Input HandlingSelect either:
- Input Manager (Old)
or - Both
If you choose Both, your legacy Input API calls should work alongside the new Input System.
If you want to keep using the legacy Input, this is the quickest fix.
Option 2: Use the new Input System API in your code
Since your project is set to use the new Input System, you should change your input code to use
UnityEngine.InputSystem.Example: Instead of
if (Input.GetKey(KeyCode.Space)) { ... }You use:
using UnityEngine.InputSystem; // add this namespace if (Keyboard.current.spaceKey.isPressed) { ... }This requires re-writing the input-related code.
Option 3: Use compiler directives to support both input systems
You can write the code that works depending on the input system active:
#if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER using UnityEngine.InputSystem; #endif // inside your function #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER if (Keyboard.current.eKey.isPressed) { // your logic } #else if (Input.GetKey(KeyCode.E)) { // your logic } #endif
How does this apply to your case?
The error says it happens in:
Fabgrid.Brush.EvaluatePreConditionsline 41 inBrush.cswhere you have:Input.GetKey(...) // legacy input usageYou need to replace this legacy call to use the new Input System API or switch your project setting to allow legacy input API.
Summary
-
If you want a quick fix:
Set Active Input Handling to Both or Input Manager (Old) in Player Settings. -
For long term and new projects:
Migrate your input code to the new Input System APIs fromUnityEngine.InputSystem.
If you want, I can help you rewrite the input-related code in your script to use the new Input System. Just share the relevant code snippet around the error (around line 41 in
Brush.cs). - Input Manager (Old)
- User
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.Collections.Generic.List`1[T].RemoveAt (System.Int32 index) (at :0) Fabgrid.Tool.HandleRemoveExistingTile (UnityEngine.GameObject tile) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:82) Fabgrid.Tool.CreateTileAt (UnityEngine.Vector3 position) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:67) Fabgrid.Brush.OnMouseDown (UnityEngine.Event e) (at Assets/Fabgrid/Scripts/Editor/Tools/Brush.cs:33) Fabgrid.Paint.OnMouseDown (UnityEngine.Event e) (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:602) Fabgrid.EventHandler.ProcessEvents (UnityEngine.Event e, Fabgrid.Tool currentTool) (at Assets/Fabgrid/Scripts/Editor/EventHandler.cs:38) Fabgrid.Paint.OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:294) Fabgrid.FSM.OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/FSM.cs:19) Fabgrid.Tilemap3DEditor.OnDuringSceneGUI (UnityEditor.SceneView sceneView) (at Assets/Fabgrid/Scripts/Editor/Tilemap3DEditor.cs:139) UnityEditor.SceneView.CallOnSceneGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEditor.SceneView.HandleSelectionAndOnSceneGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEditor.SceneView.DoOnGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEditor.SceneView.OnSceneGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, UnityEngine.Matrix4x4 worldTransform, UnityEngine.Rect clippingRect, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.SendEventToIMGUIRaw (UnityEngine.UIElements.EventBase evt, System.Boolean canAffectFocus, System.Boolean verifyBounds) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.SendEventToIMGUI (UnityEngine.UIElements.EventBase evt, System.Boolean canAffectFocus, System.Boolean verifyBounds) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.ProcessEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.CallbackEventHandler.HandleEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.CallbackEventHandler.HandleEventAtCurrentTargetAndPhase (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.CallbackEventHandler.UnityEngine.UIElements.IEventHandler.HandleEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatchUtilities.HandleEventAcrossPropagationPath (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatchUtilities.PropagateEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.MouseEventDispatchingStrategy.SendEventToRegularTarget (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.BaseVisualElementPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.MouseEventDispatchingStrategy.SendEventToTarget (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.BaseVisualElementPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.MouseEventDispatchingStrategy.DispatchEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel iPanel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ApplyDispatchingStrategies (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel, System.Boolean imguiEventIsInitiallyUsed) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ProcessEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ProcessEventQueue () (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.OpenGate () (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcherGate.Dispose () (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ProcessEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.Dispatch (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel, UnityEngine.UIElements.DispatchMode dispatchMode) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.BaseVisualElementPanel.SendEvent (UnityEngine.UIElements.EventBase e, UnityEngine.UIElements.DispatchMode dispatchMode) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& eventHandled) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIEventRegistration.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIEventRegistration+<>c.<.cctor>b__1_2 (System.Int32 i, System.IntPtr ptr) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& result) (at <9c5fbd2c5ba0433bb47ffef5ab9945cd>:0)
- Assistant
The exception
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.Collections.Generic.List`1[T].RemoveAt (System.Int32 index)indicates that somewhere in your code you call
RemoveAt(index)on aList<T>with an invalidindex—either negative or greater or equal to the list'sCount.From the stack trace:
Fabgrid.Tool.HandleRemoveExistingTile (UnityEngine.GameObject tile) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:82) Fabgrid.Tool.CreateTileAt (UnityEngine.Vector3 position) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:67)The issue happens inside
HandleRemoveExistingTileinTool.csat line 82.
How to fix the error
You need to check the code around line 82 in
Tool.csin theHandleRemoveExistingTilemethod.Most likely, you are doing something like:
int index = yourList.IndexOf(something); yourList.RemoveAt(index);But if
IndexOfreturns-1(meaning the item was not found), thenRemoveAt(-1)throws this exception.
What to do:
Add a check to verify the index is valid before calling
RemoveAt:int index = yourList.IndexOf(something); if (index >= 0 && index < yourList.Count) { yourList.RemoveAt(index); } else { Debug.LogWarning("Trying to remove an item that does not exist in the list."); }or if you directly have the index guaranteed valid, ensure the input data is correct.
If you want a concrete example, here is a hypothetical snippet:
public void HandleRemoveExistingTile(GameObject tile) { // Assuming _tiles is a List<GameObject> or similar int index = _tiles.IndexOf(tile); if (index >= 0) { _tiles.RemoveAt(index); Debug.Log("Removed tile at index " + index); } else { Debug.LogWarning("Tile not found in the list: " + tile.name); } }
Recap
- Find where
RemoveAtis called (line 82). - Before calling, always check that the index is within range
(>= 0 && < list.Count). - If the index is invalid, don't call
RemoveAt. Optionally log a warning for debugging. - Also, investigate why an invalid item/index is passed—maybe your list doesn't contain that tile or some state is out of sync.
If you want, share the code around line 82 in
Tool.csand I can help you fix it exactly. - Find where
- User
fix it and show the whole code and comments. Do not stop until you show the full code, ready to copy and paste
#if UNITY_EDITOR
using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using UnityEngine.Assertions;
namespace Fabgrid { public abstract class Tool { protected Tilemap3D tilemap; protected TilePositionCalculator positionCalculator; protected ToolType toolType; private Camera camera;
public const float MAX_PLACE_DISTANCE = 140f; protected Tool(Tilemap3D tilemap) { this.tilemap = tilemap; positionCalculator = CreateTilePositionCalculator(); } private TilePositionCalculator CreateTilePositionCalculator() { switch (tilemap.snapOption) { case SnapOption.Adaptive: return new AdaptiveTilePositionCalculator(tilemap); case SnapOption.Floor: return new FloorTilePositionCalculator(tilemap); case SnapOption.Mesh: return new MeshTilePositionCalculator(tilemap); case SnapOption.Grid: return new GridTilePositionCalculator(tilemap); default: return new AdaptiveTilePositionCalculator(tilemap); } } public void CreateTileAt(Vector3 position) { if (position.IsInfinity()) return; if (camera == null) camera = Camera.current; if (Vector3.Distance(camera.transform.position, position) > MAX_PLACE_DISTANCE) return; GameObject tile = (GameObject)PrefabUtility.InstantiatePrefab(tilemap.selectedTile.prefab); if (tilemap.selectedLayer != null) tile.transform.SetParent(tilemap.selectedLayer.transform); else tile.transform.SetParent(tilemap.transform); tile.transform.position = position; tile.transform.rotation = tilemap.tileRotation; Undo.RegisterCreatedObjectUndo(tile, "Placed tile"); if (tilemap.replaceExistingTile) HandleRemoveExistingTile(tile); tilemap.instantiatedTiles.Add(tile); tilemap.instantiatedTilePositions.Add(tile.transform.position); } private void HandleRemoveExistingTile(GameObject tile) { Assert.IsTrue(tilemap.instantiatedTiles.Count == tilemap.instantiatedTiles.Count); for (int i = tilemap.instantiatedTiles.Count - 1; i >= 0; --i) { if (tilemap.instantiatedTiles[i] == null) { tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); continue; } if (Vector3.Distance(tile.transform.position, tilemap.instantiatedTilePositions[i]) < 0.001f) { Undo.DestroyObjectImmediate(tilemap.instantiatedTiles[i]); tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); } } } public virtual void OnDestroy() { } public virtual void OnMouseDown(Event e) { } public virtual void OnMouseUp(Event e) { } public virtual void OnMouseDrag(Event e) { } public virtual void OnMouseMove(Event e) { } public virtual void OnRender(Event e) { } public virtual void OnKeyDown(Event e) { } public virtual void OnKeyUp(Event e) { } }}
#endif
- Assistant
Here is your fixed and fully ready-to-copy
Toolclass with comments and a proper bounds check to avoid theArgumentOutOfRangeException. Also fixed the incorrect assertion and added detailed comments explaining the logic.// —————————————————— // File: Tool.cs // Location: Assets/Fabgrid/Scripts/Editor/Tools/ // ——————————————————
#if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Assertions; namespace Fabgrid { public abstract class Tool { protected Tilemap3D tilemap; protected TilePositionCalculator positionCalculator; protected ToolType toolType; private Camera camera; public const float MAX_PLACE_DISTANCE = 140f; /// <summary> /// Constructor for Tool. Creates appropriate tile position calculator per tilemap's snap option. /// </summary> /// <param name="tilemap">Tilemap3D instance reference</param> protected Tool(Tilemap3D tilemap) { this.tilemap = tilemap; positionCalculator = CreateTilePositionCalculator(); } /// <summary> /// Factory method to create tile position calculator based on snap option selected on tilemap /// </summary> /// <returns>TilePositionCalculator instance</returns> private TilePositionCalculator CreateTilePositionCalculator() { switch (tilemap.snapOption) { case SnapOption.Adaptive: return new AdaptiveTilePositionCalculator(tilemap); case SnapOption.Floor: return new FloorTilePositionCalculator(tilemap); case SnapOption.Mesh: return new MeshTilePositionCalculator(tilemap); case SnapOption.Grid: return new GridTilePositionCalculator(tilemap); default: return new AdaptiveTilePositionCalculator(tilemap); } } /// <summary> /// Instantiates and places a tile GameObject at the given position, respecting placement constraints and settings. /// </summary> /// <param name="position">World position where the tile should be created</param> public void CreateTileAt(Vector3 position) { // Early out if position contains invalid values if (position.IsInfinity()) return; // Cache current camera if null if (camera == null) camera = Camera.current; // Limit tile placement distance from camera if (Vector3.Distance(camera.transform.position, position) > MAX_PLACE_DISTANCE) return; // Instantiate tile prefab as GameObject GameObject tile = (GameObject)PrefabUtility.InstantiatePrefab(tilemap.selectedTile.prefab); // Set parent transform (selected layer or fallback to tilemap) if (tilemap.selectedLayer != null) tile.transform.SetParent(tilemap.selectedLayer.transform); else tile.transform.SetParent(tilemap.transform); tile.transform.position = position; tile.transform.rotation = tilemap.tileRotation; // Register the creation for undo support Undo.RegisterCreatedObjectUndo(tile, "Placed tile"); // If replace option is enabled, remove any existing tile at this position if (tilemap.replaceExistingTile) HandleRemoveExistingTile(tile); // Add new tile and its position to the instantiated lists tilemap.instantiatedTiles.Add(tile); tilemap.instantiatedTilePositions.Add(tile.transform.position); } /// <summary> /// Checks for existing tiles at the same position as the provided tile and removes them. /// Uses a reverse for-loop to safely remove from the lists while iterating. /// </summary> /// <param name="tile">The GameObject tile to compare positions against</param> private void HandleRemoveExistingTile(GameObject tile) { // Verify that the tile list and position list always have the same count Assert.AreEqual(tilemap.instantiatedTiles.Count, tilemap.instantiatedTilePositions.Count); // Iterate backwards to safely remove items while iterating for (int i = tilemap.instantiatedTiles.Count - 1; i >= 0; --i) { // If the tile reference is null, remove it and the corresponding position if (tilemap.instantiatedTiles[i] == null) { tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); continue; } // Check if any existing tile is at approximately the same position (threshold 0.001f) if (Vector3.Distance(tile.transform.position, tilemap.instantiatedTilePositions[i]) < 0.001f) { // Destroy the existing tile gameobject and remove from lists Undo.DestroyObjectImmediate(tilemap.instantiatedTiles[i]); tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); } } } // Virtual event handlers that derived tools can override to respond to user input/interaction public virtual void OnDestroy() { } public virtual void OnMouseDown(Event e) { } public virtual void OnMouseUp(Event e) { } public virtual void OnMouseDrag(Event e) { } public virtual void OnMouseMove(Event e) { } public virtual void OnRender(Event e) { } public virtual void OnKeyDown(Event e) { } public virtual void OnKeyUp(Event e) { } } } #endif
Explanation of the fix
- The original assertion was
Assert.IsTrue(tilemap.instantiatedTiles.Count == tilemap.instantiatedTiles.Count);which compared the same property → redundant. Changed to:
Assert.AreEqual(tilemap.instantiatedTiles.Count, tilemap.instantiatedTilePositions.Count);to ensure list counts are equal (critical for removing paired elements by index).
-
The removal loop is a reverse iteration so removing items during iteration is safe and won't cause index errors.
-
Before removing at index
i, the code verifies that the tile reference is valid or at the right position to remove. -
This logic ensures no invalid
RemoveAtcalls occur (becauseiranges over the actual valid range).
With these safeguards, your
ArgumentOutOfRangeExceptionshould no longer occur.Let me know if you want help fixing other scripts or integrating with the new Input System!
- The original assertion was
- User
AssertionException: Assertion failure. Values are not equal. Expected: 0 == 198 UnityEngine.Assertions.Assert.Fail (System.String message, System.String userMessage) (at <5eddeaad60a14d8ab4eb3a7453824232>:0) UnityEngine.Assertions.Assert.AreEqual[T] (T expected, T actual, System.String message, System.Collections.Generic.IEqualityComparer`1[T] comparer) (at <5eddeaad60a14d8ab4eb3a7453824232>:0) UnityEngine.Assertions.Assert.AreEqual[T] (T expected, T actual, System.String message) (at <5eddeaad60a14d8ab4eb3a7453824232>:0) UnityEngine.Assertions.Assert.AreEqual (System.Int32 expected, System.Int32 actual) (at <5eddeaad60a14d8ab4eb3a7453824232>:0) Fabgrid.Tool.HandleRemoveExistingTile (UnityEngine.GameObject tile) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:104) Fabgrid.Tool.CreateTileAt (UnityEngine.Vector3 position) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:89) Fabgrid.Brush.OnMouseDown (UnityEngine.Event e) (at Assets/Fabgrid/Scripts/Editor/Tools/Brush.cs:33) Fabgrid.Paint.OnMouseDown (UnityEngine.Event e) (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:602) Fabgrid.EventHandler.ProcessEvents (UnityEngine.Event e, Fabgrid.Tool currentTool) (at Assets/Fabgrid/Scripts/Editor/EventHandler.cs:38) Fabgrid.Paint.OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:294) Fabgrid.FSM.OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/FSM.cs:19) Fabgrid.Tilemap3DEditor.OnDuringSceneGUI (UnityEditor.SceneView sceneView) (at Assets/Fabgrid/Scripts/Editor/Tilemap3DEditor.cs:139) UnityEditor.SceneView.CallOnSceneGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEditor.SceneView.HandleSelectionAndOnSceneGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEditor.SceneView.DoOnGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEditor.SceneView.OnSceneGUI () (at <1378b88fef4c46d398a0261fcd723ab7>:0) UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, UnityEngine.Matrix4x4 worldTransform, UnityEngine.Rect clippingRect, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, System.Boolean canAffectFocus) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.SendEventToIMGUIRaw (UnityEngine.UIElements.EventBase evt, System.Boolean canAffectFocus, System.Boolean verifyBounds) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.SendEventToIMGUI (UnityEngine.UIElements.EventBase evt, System.Boolean canAffectFocus, System.Boolean verifyBounds) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.IMGUIContainer.ProcessEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.CallbackEventHandler.HandleEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.CallbackEventHandler.HandleEventAtCurrentTargetAndPhase (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.CallbackEventHandler.UnityEngine.UIElements.IEventHandler.HandleEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatchUtilities.HandleEventAcrossPropagationPath (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatchUtilities.PropagateEvent (UnityEngine.UIElements.EventBase evt) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.MouseEventDispatchingStrategy.SendEventToRegularTarget (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.BaseVisualElementPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.MouseEventDispatchingStrategy.SendEventToTarget (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.BaseVisualElementPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.MouseEventDispatchingStrategy.DispatchEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel iPanel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ApplyDispatchingStrategies (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel, System.Boolean imguiEventIsInitiallyUsed) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ProcessEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ProcessEventQueue () (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.OpenGate () (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcherGate.Dispose () (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.ProcessEvent (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.EventDispatcher.Dispatch (UnityEngine.UIElements.EventBase evt, UnityEngine.UIElements.IPanel panel, UnityEngine.UIElements.DispatchMode dispatchMode) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.BaseVisualElementPanel.SendEvent (UnityEngine.UIElements.EventBase e, UnityEngine.UIElements.DispatchMode dispatchMode) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& eventHandled) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIEventRegistration.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.UIElements.UIEventRegistration+<>c.<.cctor>b__1_2 (System.Int32 i, System.IntPtr ptr) (at <7e0d8599f75e4147aee4a8bbf5406b00>:0) UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& result) (at <9c5fbd2c5ba0433bb47ffef5ab9945cd>:0)
- Assistant
The assertion failure:
AssertionException: Assertion failure. Values are not equal. Expected: 0 == 198indicates that inside your
HandleRemoveExistingTilemethod you have the assertion:Assert.AreEqual(tilemap.instantiatedTiles.Count, tilemap.instantiatedTilePositions.Count);but one list's count is 198 and the other is 0, meaning the lists lost synchronization.
Root cause
It means somewhere in your code, the two lists :
tilemap.instantiatedTilestilemap.instantiatedTilePositions
are getting out of sync—they should always have the same number of elements, since each index corresponds to a tile and its position.
How to fix it
1. Remove or replace the assertion with a safer check
At least avoid crashing with the assertion and instead log an error and early exit to prevent corrupting state:
private void HandleRemoveExistingTile(GameObject tile) { if (tilemap.instantiatedTiles.Count != tilemap.instantiatedTilePositions.Count) { Debug.LogError($"Mismatched instantiated tiles and positions counts: {tilemap.instantiatedTiles.Count} vs {tilemap.instantiatedTilePositions.Count}! Aborting removal."); return; } // rest of removal logic ... }This prevents invalid
RemoveAtcalls when counts differ.
2. Investigate why the lists desynchronize and fix that root cause
- Make sure everywhere you add or remove a tile, you also add or remove the corresponding position entry at the same time.
- Look for any code paths adding/removing ONLY from one list but not the other.
- The lists must always stay in sync.
3. Add safety checks in other parts of your code working with these lists
For example, when you add a tile:
tilemap.instantiatedTiles.Add(tile); tilemap.instantiatedTilePositions.Add(tile.transform.position);When removing tiles make sure you remove from both.
Full updated
Toolclass with safer checks and logging#if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Assertions; namespace Fabgrid { public abstract class Tool { protected Tilemap3D tilemap; protected TilePositionCalculator positionCalculator; protected ToolType toolType; private Camera camera; public const float MAX_PLACE_DISTANCE = 140f; protected Tool(Tilemap3D tilemap) { this.tilemap = tilemap; positionCalculator = CreateTilePositionCalculator(); } private TilePositionCalculator CreateTilePositionCalculator() { switch (tilemap.snapOption) { case SnapOption.Adaptive: return new AdaptiveTilePositionCalculator(tilemap); case SnapOption.Floor: return new FloorTilePositionCalculator(tilemap); case SnapOption.Mesh: return new MeshTilePositionCalculator(tilemap); case SnapOption.Grid: return new GridTilePositionCalculator(tilemap); default: return new AdaptiveTilePositionCalculator(tilemap); } } public void CreateTileAt(Vector3 position) { if (position.IsInfinity()) return; if (camera == null) camera = Camera.current; if (Vector3.Distance(camera.transform.position, position) > MAX_PLACE_DISTANCE) return; GameObject tile = (GameObject)PrefabUtility.InstantiatePrefab(tilemap.selectedTile.prefab); if (tilemap.selectedLayer != null) tile.transform.SetParent(tilemap.selectedLayer.transform); else tile.transform.SetParent(tilemap.transform); tile.transform.position = position; tile.transform.rotation = tilemap.tileRotation; Undo.RegisterCreatedObjectUndo(tile, "Placed tile"); if (tilemap.replaceExistingTile) HandleRemoveExistingTile(tile); tilemap.instantiatedTiles.Add(tile); tilemap.instantiatedTilePositions.Add(tile.transform.position); } private void HandleRemoveExistingTile(GameObject tile) { // Check counts are equal, if not log error and don't proceed to avoid crash/damage if (tilemap.instantiatedTiles.Count != tilemap.instantiatedTilePositions.Count) { Debug.LogError($"[HandleRemoveExistingTile] instantiatedTiles count ({tilemap.instantiatedTiles.Count}) " + $"!= instantiatedTilePositions count ({tilemap.instantiatedTilePositions.Count}). Aborting removal!"); return; } for (int i = tilemap.instantiatedTiles.Count - 1; i >= 0; --i) { var existingTile = tilemap.instantiatedTiles[i]; if (existingTile == null) { tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); continue; } if (Vector3.Distance(tile.transform.position, tilemap.instantiatedTilePositions[i]) < 0.001f) { Undo.DestroyObjectImmediate(existingTile); tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); } } } public virtual void OnDestroy() { } public virtual void OnMouseDown(Event e) { } public virtual void OnMouseUp(Event e) { } public virtual void OnMouseDrag(Event e) { } public virtual void OnMouseMove(Event e) { } public virtual void OnRender(Event e) { } public virtual void OnKeyDown(Event e) { } public virtual void OnKeyUp(Event e) { } } } #endif
Debugging Tips if Problem Persists
- Add debug logs just before any
AddorRemoveAtoperations on those lists to track how/when desynchronization happens. - Search your whole project for all places where
instantiatedTilesand/orinstantiatedTilePositionsare modified. - If you find code that modifies one without the other, fix it to keep them in sync, or encapsulate list management behind methods to ensure consistency.
If you want, I can help you audit other related code to ensure your tile lists stay consistent.
- User
[HandleRemoveExistingTile] instantiatedTiles count (202) != instantiatedTilePositions count (4). Aborting removal! UnityEngine.Debug:LogError (object) Fabgrid.Tool:HandleRemoveExistingTile (UnityEngine.GameObject) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:77) Fabgrid.Tool:CreateTileAt (UnityEngine.Vector3) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:66) Fabgrid.Brush:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/Tools/Brush.cs:33) Fabgrid.Paint:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:602) Fabgrid.EventHandler:ProcessEvents (UnityEngine.Event,Fabgrid.Tool) (at Assets/Fabgrid/Scripts/Editor/EventHandler.cs:38) Fabgrid.Paint:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:294) Fabgrid.FSM:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/FSM.cs:19) Fabgrid.Tilemap3DEditor:OnDuringSceneGUI (UnityEditor.SceneView) (at Assets/Fabgrid/Scripts/Editor/Tilemap3DEditor.cs:139) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
- Assistant
The core issue remains: the two lists
tilemap.instantiatedTiles(currently 202 elements)tilemap.instantiatedTilePositions(currently 4 elements)
are wildly out of sync — one has 202 items, the other only 4.
This absolutely must be fixed at the source — your code is adding/removing tiles and positions unevenly.
Why does this happen?
Your
Toolclass adds and removes items from these two different lists every time a tile is created or destroyed.If any other part of your code adds/removes items from one list but not the other, or directly manipulates one of them, you get desync.
How to fix it properly
You must centralize and encapsulate all modifications in a way that guarantees both lists are updated atomically, so they never diverge.
Proposal: Wrap these two lists inside a new managed structure or methods
1) Create helper methods inside
Tilemap3DorToolto add and remove tiles safely:// Inside Tool or Tilemap3D: private void AddInstantiatedTile(GameObject tile) { tilemap.instantiatedTiles.Add(tile); tilemap.instantiatedTilePositions.Add(tile.transform.position); } private void RemoveInstantiatedTileAt(int index) { tilemap.instantiatedTiles.RemoveAt(index); tilemap.instantiatedTilePositions.RemoveAt(index); }2) Always call these exclusively to add or remove tiles.
3) Update
CreateTileAt()to use these methods instead of direct list manipulation:public void CreateTileAt(Vector3 position) { if (position.IsInfinity()) return; if (camera == null) camera = Camera.current; if (Vector3.Distance(camera.transform.position, position) > MAX_PLACE_DISTANCE) return; GameObject tile = (GameObject)PrefabUtility.InstantiatePrefab(tilemap.selectedTile.prefab); if (tilemap.selectedLayer != null) tile.transform.SetParent(tilemap.selectedLayer.transform); else tile.transform.SetParent(tilemap.transform); tile.transform.position = position; tile.transform.rotation = tilemap.tileRotation; Undo.RegisterCreatedObjectUndo(tile, "Placed tile"); if (tilemap.replaceExistingTile) HandleRemoveExistingTile(tile); AddInstantiatedTile(tile); // Use the new helper }4) Update
HandleRemoveExistingTileto useRemoveInstantiatedTileAt(i)instead of manually removing:private void HandleRemoveExistingTile(GameObject tile) { if (tilemap.instantiatedTiles.Count != tilemap.instantiatedTilePositions.Count) { Debug.LogError($"[HandleRemoveExistingTile] instantiatedTiles count ({tilemap.instantiatedTiles.Count}) != instantiatedTilePositions count ({tilemap.instantiatedTilePositions.Count}). Aborting removal!"); return; } for (int i = tilemap.instantiatedTiles.Count - 1; i >= 0; --i) { var existingTile = tilemap.instantiatedTiles[i]; if (existingTile == null) { RemoveInstantiatedTileAt(i); // Use helper continue; } if (Vector3.Distance(tile.transform.position, tilemap.instantiatedTilePositions[i]) < 0.001f) { Undo.DestroyObjectImmediate(existingTile); RemoveInstantiatedTileAt(i); // Use helper } } }
Most likely some other script or method is modifying one list directly without touching the other!
- Search your project for all usage of
tilemap.instantiatedTilesandtilemap.instantiatedTilePositions. - Refactor any direct manipulation to go through your new add/remove helper methods.
- If you can't refactor other code, at least apply runtime checks or keep these lists private and wrap access.
FULL UPDATED Tool.cs with helpers and fixed usage
#if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Assertions; namespace Fabgrid { public abstract class Tool { protected Tilemap3D tilemap; protected TilePositionCalculator positionCalculator; protected ToolType toolType; private Camera camera; public const float MAX_PLACE_DISTANCE = 140f; protected Tool(Tilemap3D tilemap) { this.tilemap = tilemap; positionCalculator = CreateTilePositionCalculator(); } private TilePositionCalculator CreateTilePositionCalculator() { switch (tilemap.snapOption) { case SnapOption.Adaptive: return new AdaptiveTilePositionCalculator(tilemap); case SnapOption.Floor: return new FloorTilePositionCalculator(tilemap); case SnapOption.Mesh: return new MeshTilePositionCalculator(tilemap); case SnapOption.Grid: return new GridTilePositionCalculator(tilemap); default: return new AdaptiveTilePositionCalculator(tilemap); } } /// <summary> /// Add tile and position atomically to keep lists synchronized. /// </summary> /// <param name="tile">Tile GameObject</param> private void AddInstantiatedTile(GameObject tile) { tilemap.instantiatedTiles.Add(tile); tilemap.instantiatedTilePositions.Add(tile.transform.position); } /// <summary> /// Remove tile and position by index atomically to keep lists synchronized. /// </summary> /// <param name="index">Index to remove</param> private void RemoveInstantiatedTileAt(int index) { tilemap.instantiatedTiles.RemoveAt(index); tilemap.instantiatedTilePositions.RemoveAt(index); } public void CreateTileAt(Vector3 position) { if (position.IsInfinity()) return; if (camera == null) camera = Camera.current; if (Vector3.Distance(camera.transform.position, position) > MAX_PLACE_DISTANCE) return; GameObject tile = (GameObject)PrefabUtility.InstantiatePrefab(tilemap.selectedTile.prefab); if (tilemap.selectedLayer != null) tile.transform.SetParent(tilemap.selectedLayer.transform); else tile.transform.SetParent(tilemap.transform); tile.transform.position = position; tile.transform.rotation = tilemap.tileRotation; Undo.RegisterCreatedObjectUndo(tile, "Placed tile"); if (tilemap.replaceExistingTile) HandleRemoveExistingTile(tile); AddInstantiatedTile(tile); } private void HandleRemoveExistingTile(GameObject tile) { if (tilemap.instantiatedTiles.Count != tilemap.instantiatedTilePositions.Count) { Debug.LogError($"[HandleRemoveExistingTile] instantiatedTiles count ({tilemap.instantiatedTiles.Count}) != instantiatedTilePositions count ({tilemap.instantiatedTilePositions.Count}). Aborting removal!"); return; } for (int i = tilemap.instantiatedTiles.Count - 1; i >= 0; --i) { var existingTile = tilemap.instantiatedTiles[i]; if (existingTile == null) { RemoveInstantiatedTileAt(i); continue; } if (Vector3.Distance(tile.transform.position, tilemap.instantiatedTilePositions[i]) < 0.001f) { Undo.DestroyObjectImmediate(existingTile); RemoveInstantiatedTileAt(i); } } } public virtual void OnDestroy() {} public virtual void OnMouseDown(Event e) {} public virtual void OnMouseUp(Event e) {} public virtual void OnMouseDrag(Event e) {} public virtual void OnMouseMove(Event e) {} public virtual void OnRender(Event e) {} public virtual void OnKeyDown(Event e) {} public virtual void OnKeyUp(Event e) {} } } #endif
Final notes:
- This change alone will not fix the problem if other scripts modify either list directly.
- You must audit your codebase and restrict modifications to the new helper methods.
- You may want to make the lists
privateorinternaland expose safe accessors.
If you want, I can help review the rest of your project for list desynchronization risks — just share relevant code or usages.
- User
[HandleRemoveExistingTile] instantiatedTiles count (204) != instantiatedTilePositions count (6). Aborting removal! UnityEngine.Debug:LogError (object) Fabgrid.Tool:HandleRemoveExistingTile (UnityEngine.GameObject) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:94) Fabgrid.Tool:CreateTileAt (UnityEngine.Vector3) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:85) Fabgrid.Brush:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/Tools/Brush.cs:33) Fabgrid.Paint:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:602) Fabgrid.EventHandler:ProcessEvents (UnityEngine.Event,Fabgrid.Tool) (at Assets/Fabgrid/Scripts/Editor/EventHandler.cs:38) Fabgrid.Paint:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:294) Fabgrid.FSM:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/FSM.cs:19) Fabgrid.Tilemap3DEditor:OnDuringSceneGUI (UnityEditor.SceneView) (at Assets/Fabgrid/Scripts/Editor/Tilemap3DEditor.cs:139) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
- Assistant
The root issue is still there:
tilemap.instantiatedTilescount (204) !=tilemap.instantiatedTilePositionscount (6) indicates your two lists are out of sync.
This problem cannot be solved just inside the
Toolclass:You said counts differ by +198 items in
instantiatedTileslist compared toinstantiatedTilePositions.
That means somewhere else in your code (not shown) these lists are being modified independently and inconsistently.
What you need to do next:
1) Find ALL code that accesses or modifies
tilemap.instantiatedTilesandtilemap.instantiatedTilePositionsTo do this:
-
Search your entire project for any usage of these two lists:
tilemap.instantiatedTiles
tilemap.instantiatedTilePositions -
Look especially for code that calls
.Add(),.Remove(),.RemoveAt(),.Clear(),.Insert(), etc., on either of these lists. -
Identify any code that modifies only one of the lists without modifying the other.
2) Refactor or fix those code sections, so both lists are always updated together
Your lists represent parallel arrays — they must be kept perfectly in sync, with the same count and corresponding indices.
Never add to or remove from one list without doing the exact same to the other!
3) Strongly Consider The Following Best Practices:
- Make these two lists private inside
Tilemap3D, so external code can't modify them directly. - Create a single manager class or methods on
Tilemap3Dto add/remove tiles and positions atomically. - Expose only methods like
AddTile(GameObject tile),RemoveTileAt(int index), etc. - Weakening the lists' direct public access reduces the chance of desync mistakes.
- If you want, the lists can be exposed as read-only collections (
IReadOnlyList<T>), but all modifications must go through your methods.
4) Example of concept in
Tilemap3D:public class Tilemap3D : MonoBehaviour { [SerializeField] private List<GameObject> instantiatedTiles = new List<GameObject>(); [SerializeField] private List<Vector3> instantiatedTilePositions = new List<Vector3>(); public int TileCount => instantiatedTiles.Count; public IReadOnlyList<GameObject> InstantiatedTiles => instantiatedTiles.AsReadOnly(); public IReadOnlyList<Vector3> InstantiatedTilePositions => instantiatedTilePositions.AsReadOnly(); public void AddTile(GameObject tile) { instantiatedTiles.Add(tile); instantiatedTilePositions.Add(tile.transform.position); } public void RemoveTileAt(int index) { instantiatedTiles.RemoveAt(index); instantiatedTilePositions.RemoveAt(index); } // Other methods... // You may want a method to safely clear all tiles: public void ClearTiles() { instantiatedTiles.Clear(); instantiatedTilePositions.Clear(); } }
5) Then, in your
Toolclass, always call these methods:// Instead of direct adds/removes... tilemap.AddTile(tile);tilemap.RemoveTileAt(i);
6) To track down the cause of desync, add debug logging everywhere these lists are modified before the fix:
Debug.Log($"AddTile called. Tiles count before: {instantiatedTiles.Count}, Positions count before: {instantiatedTilePositions.Count}");And similar for remove.
Final Notes
- Until you audit all usages and refactor accordingly, your lists will remain out of sync.
- This is the root cause, not a symptom you fix by checks alone.
- The assertion/abort is a good guard — it prevents the crash due to out-of-range removals — but does not fix data corruption.
If you provide or want me to review all other scripts where you manipulate
instantiatedTilesorinstantiatedTilePositions, I can help pinpoint where the desync happens.
Summary:
- Make the two lists private.
- Wrap access with synchronized add/remove methods.
- Refactor all external code to use those methods only.
- Audit and fix other usages breaking sync.
If you want a fully refactored example with wrapped lists, interactions, and error logging, just ask!
-
- User
shwo the full fixed code
- Assistant
Certainly! Below is a full refactor example that fixes your problem by encapsulating the two lists inside your
Tilemap3Dclass, making them private, and providing atomic add/remove methods. YourToolclass then calls those methods instead of manipulating the lists directly.
1) Refactored
Tilemap3DclassManages tile lists safely, exposes only atomic methods.
using System.Collections.Generic; using UnityEngine; namespace Fabgrid { public class Tilemap3D : MonoBehaviour { [SerializeField] private List<GameObject> instantiatedTiles = new List<GameObject>(); [SerializeField] private List<Vector3> instantiatedTilePositions = new List<Vector3>(); // Expose readonly copies to read from outside, but not modify public IReadOnlyList<GameObject> InstantiatedTiles => instantiatedTiles.AsReadOnly(); public IReadOnlyList<Vector3> InstantiatedTilePositions => instantiatedTilePositions.AsReadOnly(); public int TileCount => instantiatedTiles.Count; /// <summary> /// Adds a tile and its position atomically to keep lists in sync. /// </summary> public void AddTile(GameObject tile) { if (tile == null) { Debug.LogWarning("Attempted to add null tile to Tilemap3D."); return; } instantiatedTiles.Add(tile); instantiatedTilePositions.Add(tile.transform.position); Debug.Log($"[Tilemap3D] Added tile at position {tile.transform.position}. " + $"Total tiles: {instantiatedTiles.Count}"); } /// <summary> /// Removes tile and corresponding position by index atomically. /// </summary> public void RemoveTileAt(int index) { if (index < 0 || index >= instantiatedTiles.Count) { Debug.LogError($"[Tilemap3D] RemoveTileAt invalid index {index}. Count: {instantiatedTiles.Count}"); return; } instantiatedTiles.RemoveAt(index); instantiatedTilePositions.RemoveAt(index); Debug.Log($"[Tilemap3D] Removed tile at index {index}. Remaining tiles: {instantiatedTiles.Count}"); } /// <summary> /// Clears all tiles and positions. /// </summary> public void ClearTiles() { instantiatedTiles.Clear(); instantiatedTilePositions.Clear(); Debug.Log("[Tilemap3D] Cleared all tiles."); } // Optionally add more safe methods for managing tiles here } }
2) Refactored
ToolclassCalls only the safe methods of
Tilemap3D.#if UNITY_EDITOR using UnityEditor; using UnityEngine; using UnityEngine.Assertions; namespace Fabgrid { public abstract class Tool { protected Tilemap3D tilemap; protected TilePositionCalculator positionCalculator; protected ToolType toolType; private Camera camera; public const float MAX_PLACE_DISTANCE = 140f; protected Tool(Tilemap3D tilemap) { this.tilemap = tilemap; positionCalculator = CreateTilePositionCalculator(); } private TilePositionCalculator CreateTilePositionCalculator() { switch (tilemap.snapOption) { case SnapOption.Adaptive: return new AdaptiveTilePositionCalculator(tilemap); case SnapOption.Floor: return new FloorTilePositionCalculator(tilemap); case SnapOption.Mesh: return new MeshTilePositionCalculator(tilemap); case SnapOption.Grid: return new GridTilePositionCalculator(tilemap); default: return new AdaptiveTilePositionCalculator(tilemap); } } /// <summary> /// Creates a tile GameObject at the specified position if possible. /// </summary> public void CreateTileAt(Vector3 position) { if (position.IsInfinity()) return; if (camera == null) camera = Camera.current; if (Vector3.Distance(camera.transform.position, position) > MAX_PLACE_DISTANCE) return; GameObject tile = (GameObject)PrefabUtility.InstantiatePrefab(tilemap.selectedTile.prefab); if (tilemap.selectedLayer != null) tile.transform.SetParent(tilemap.selectedLayer.transform); else tile.transform.SetParent(tilemap.transform); tile.transform.position = position; tile.transform.rotation = tilemap.tileRotation; Undo.RegisterCreatedObjectUndo(tile, "Placed tile"); if (tilemap.replaceExistingTile) HandleRemoveExistingTile(tile); // Use safe add method tilemap.AddTile(tile); } /// <summary> /// Removes any existing tiles at the same position as the passed tile. /// </summary> private void HandleRemoveExistingTile(GameObject tile) { // Make sure internal lists are synchronized by using Tilemap3D's public count properties if (tilemap.InstantiatedTiles.Count != tilemap.InstantiatedTilePositions.Count) { Debug.LogError($"[HandleRemoveExistingTile] Tiles count ({tilemap.InstantiatedTiles.Count}) != Positions count ({tilemap.InstantiatedTilePositions.Count}). Aborting removal!"); return; } // Iterate backward over the tiles to safely remove while iterating for (int i = tilemap.InstantiatedTiles.Count - 1; i >= 0; --i) { var existingTile = tilemap.InstantiatedTiles[i]; if (existingTile == null) { tilemap.RemoveTileAt(i); continue; } if (Vector3.Distance(tile.transform.position, tilemap.InstantiatedTilePositions[i]) < 0.001f) { Undo.DestroyObjectImmediate(existingTile); tilemap.RemoveTileAt(i); } } } // Virtual event handlers to be overridden by subclasses public virtual void OnDestroy() { } public virtual void OnMouseDown(Event e) { } public virtual void OnMouseUp(Event e) { } public virtual void OnMouseDrag(Event e) { } public virtual void OnMouseMove(Event e) { } public virtual void OnRender(Event e) { } public virtual void OnKeyDown(Event e) { } public virtual void OnKeyUp(Event e) { } } } #endif
Notes:
- This fully solves your list desync problem by encapsulating the two parallel lists inside
Tilemap3Dwith private fields. - External code cannot mess up the lists by modifying only one.
- All adds/removes are done by atomic helper methods (
AddTileandRemoveTileAt). - The
Toolclass and any other code base must always use these helpers. - Your debug log messages will help track list modifications if needed.
- You should now audit your entire project for any remaining direct accesses to
tilemap.instantiatedTilesortilemap.instantiatedTilePositionsand refactor those to use the new methods.
If you want me to help you adapt other parts of your code, just share them!
- This fully solves your list desync problem by encapsulating the two parallel lists inside
- User
keep the original code, but just fix it and show all of it
- Assistant
Certainly! Below is your original
Toolclass with only the necessary fixes applied to prevent the list count desynchronization error from causing exceptions or assertion failures.What was fixed
- Removed the invalid assertion
Assert.IsTrue(tilemap.instantiatedTiles.Count == tilemap.instantiatedTiles.Count);(self equality). - Added a safe check for the two lists counts to exit early if they are out of sync and log an error.
- Used safe removal: inside
HandleRemoveExistingTile, we only remove when the lists are properly synchronized. - Added some comments to clarify the fix.
This preserves your original structure and logic but adds defensive programming to prevent exceptions.
#if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Assertions; namespace Fabgrid { public abstract class Tool { protected Tilemap3D tilemap; protected TilePositionCalculator positionCalculator; protected ToolType toolType; private Camera camera; public const float MAX_PLACE_DISTANCE = 140f; protected Tool(Tilemap3D tilemap) { this.tilemap = tilemap; positionCalculator = CreateTilePositionCalculator(); } private TilePositionCalculator CreateTilePositionCalculator() { switch (tilemap.snapOption) { case SnapOption.Adaptive: return new AdaptiveTilePositionCalculator(tilemap); case SnapOption.Floor: return new FloorTilePositionCalculator(tilemap); case SnapOption.Mesh: return new MeshTilePositionCalculator(tilemap); case SnapOption.Grid: return new GridTilePositionCalculator(tilemap); default: return new AdaptiveTilePositionCalculator(tilemap); } } public void CreateTileAt(Vector3 position) { if (position.IsInfinity()) return; if (camera == null) camera = Camera.current; if (Vector3.Distance(camera.transform.position, position) > MAX_PLACE_DISTANCE) return; GameObject tile = (GameObject)PrefabUtility.InstantiatePrefab(tilemap.selectedTile.prefab); if (tilemap.selectedLayer != null) tile.transform.SetParent(tilemap.selectedLayer.transform); else tile.transform.SetParent(tilemap.transform); tile.transform.position = position; tile.transform.rotation = tilemap.tileRotation; Undo.RegisterCreatedObjectUndo(tile, "Placed tile"); // Defensive: only try removing existing tile if lists are synchronized if (tilemap.replaceExistingTile) HandleRemoveExistingTile(tile); // Add new tile and position tilemap.instantiatedTiles.Add(tile); tilemap.instantiatedTilePositions.Add(tile.transform.position); } /// <summary> /// Removes any existing tiles that are at (almost) the same position as the input tile. /// Added early check on counts to avoid out-of-sync errors. /// </summary> private void HandleRemoveExistingTile(GameObject tile) { // Defensive check: lists must have the same count to avoid exceptions if (tilemap.instantiatedTiles.Count != tilemap.instantiatedTilePositions.Count) { Debug.LogError( $"[HandleRemoveExistingTile] instantiatedTiles count ({tilemap.instantiatedTiles.Count}) " + $"!= instantiatedTilePositions count ({tilemap.instantiatedTilePositions.Count}). Aborting removal!"); return; } // Iterate backwards to safely remove while iterating for (int i = tilemap.instantiatedTiles.Count - 1; i >= 0; --i) { // Null tiles are cleaned up if (tilemap.instantiatedTiles[i] == null) { tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); continue; } // If tile is at (almost) the same position, destroy and remove lists elements if (Vector3.Distance(tile.transform.position, tilemap.instantiatedTilePositions[i]) < 0.001f) { Undo.DestroyObjectImmediate(tilemap.instantiatedTiles[i]); tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); } } } public virtual void OnDestroy() { } public virtual void OnMouseDown(Event e) { } public virtual void OnMouseUp(Event e) { } public virtual void OnMouseDrag(Event e) { } public virtual void OnMouseMove(Event e) { } public virtual void OnRender(Event e) { } public virtual void OnKeyDown(Event e) { } public virtual void OnKeyUp(Event e) { } } } #endif
Summary of fix:
- Instead of asserting lists match, check their counts before attempting removal.
- If counts don't match, log error and skip removal to prevent exceptions.
- Other than this safety check, kept all the rest of your original code intact.
Important:
This fix is a defensive workaround. Your underlying problem (the two lists getting out of sync) must be fixed by auditing all other code that manipulates the two lists and making sure you always add/remove positions and tiles simultaneously.
If you want me to help find and fix these problems in your project, please provide code where you read/write those lists elsewhere.
Let me know if you want me to enhance this with helper add/remove methods or deeper refactor!
- Removed the invalid assertion
- User
[HandleRemoveExistingTile] instantiatedTiles count (223) != instantiatedTilePositions count (25). Aborting removal! UnityEngine.Debug:LogError (object) Fabgrid.Tool:HandleRemoveExistingTile (UnityEngine.GameObject) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:85) Fabgrid.Tool:CreateTileAt (UnityEngine.Vector3) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:69) Fabgrid.Brush:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/Tools/Brush.cs:33) Fabgrid.Paint:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:602) Fabgrid.EventHandler:ProcessEvents (UnityEngine.Event,Fabgrid.Tool) (at Assets/Fabgrid/Scripts/Editor/EventHandler.cs:38) Fabgrid.Paint:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:294) Fabgrid.FSM:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/FSM.cs:19) Fabgrid.Tilemap3DEditor:OnDuringSceneGUI (UnityEditor.SceneView) (at Assets/Fabgrid/Scripts/Editor/Tilemap3DEditor.cs:139) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Fix it and show all
- Assistant
The persistent message:
[HandleRemoveExistingTile] instantiatedTiles count (223) != instantiatedTilePositions count (25). Aborting removal!means your two lists
instantiatedTilesandinstantiatedTilePositionsare drastically out of sync because the one for tiles has 223 elements and the one for positions has 25. This must be fixed by ensuring these lists are always changed together.
You asked to "Fix it and show all" with your original structure.
Here is a minimal fix within your code that:
- Prevents exceptions/crashes by skipping removal if counts mismatch.
- Attempts to resynchronize the lists at start of
HandleRemoveExistingTileby trimming the longer list to the length of the shorter (assuming missing data). - Adds clear comments about why this is dangerous and should be fixed better upstream.
FULL fixed code for your
Toolclass:#if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Assertions; namespace Fabgrid { public abstract class Tool { protected Tilemap3D tilemap; protected TilePositionCalculator positionCalculator; protected ToolType toolType; private Camera camera; public const float MAX_PLACE_DISTANCE = 140f; protected Tool(Tilemap3D tilemap) { this.tilemap = tilemap; positionCalculator = CreateTilePositionCalculator(); } private TilePositionCalculator CreateTilePositionCalculator() { switch (tilemap.snapOption) { case SnapOption.Adaptive: return new AdaptiveTilePositionCalculator(tilemap); case SnapOption.Floor: return new FloorTilePositionCalculator(tilemap); case SnapOption.Mesh: return new MeshTilePositionCalculator(tilemap); case SnapOption.Grid: return new GridTilePositionCalculator(tilemap); default: return new AdaptiveTilePositionCalculator(tilemap); } } public void CreateTileAt(Vector3 position) { if (position.IsInfinity()) return; if (camera == null) camera = Camera.current; if (Vector3.Distance(camera.transform.position, position) > MAX_PLACE_DISTANCE) return; GameObject tile = (GameObject)PrefabUtility.InstantiatePrefab(tilemap.selectedTile.prefab); if (tilemap.selectedLayer != null) tile.transform.SetParent(tilemap.selectedLayer.transform); else tile.transform.SetParent(tilemap.transform); tile.transform.position = position; tile.transform.rotation = tilemap.tileRotation; Undo.RegisterCreatedObjectUndo(tile, "Placed tile"); if (tilemap.replaceExistingTile) HandleRemoveExistingTile(tile); tilemap.instantiatedTiles.Add(tile); tilemap.instantiatedTilePositions.Add(tile.transform.position); } /// <summary> /// This method will attempt to handle desynchronized lists by trimming the longer list /// to the size of the shorter one, preventing crashes but can cause data loss. /// Recommended: find and fix root cause elsewhere. /// </summary> private void HandleRemoveExistingTile(GameObject tile) { int tilesCount = tilemap.instantiatedTiles.Count; int positionsCount = tilemap.instantiatedTilePositions.Count; if (tilesCount != positionsCount) { Debug.LogWarning( $"[HandleRemoveExistingTile] Detected list size mismatch. " + $"instantiatedTiles count = {tilesCount}, instantiatedTilePositions count = {positionsCount}." + $" Attempting to resynchronize by trimming longer list."); // Trim the longer list to match the shorter count to avoid out-of-bounds exceptions int minCount = Mathf.Min(tilesCount, positionsCount); if (tilesCount > minCount) { Debug.LogWarning($"Trimming instantiatedTiles list from {tilesCount} to {minCount} items."); tilemap.instantiatedTiles.RemoveRange(minCount, tilesCount - minCount); } if (positionsCount > minCount) { Debug.LogWarning($"Trimming instantiatedTilePositions list from {positionsCount} to {minCount} items."); tilemap.instantiatedTilePositions.RemoveRange(minCount, positionsCount - minCount); } } // Now safe to assume counts are equal for (int i = tilemap.instantiatedTiles.Count - 1; i >= 0; --i) { GameObject existingTile = tilemap.instantiatedTiles[i]; if (existingTile == null) { tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); continue; } if (Vector3.Distance(tile.transform.position, tilemap.instantiatedTilePositions[i]) < 0.001f) { Undo.DestroyObjectImmediate(existingTile); tilemap.instantiatedTiles.RemoveAt(i); tilemap.instantiatedTilePositions.RemoveAt(i); } } } public virtual void OnDestroy() { } public virtual void OnMouseDown(Event e) { } public virtual void OnMouseUp(Event e) { } public virtual void OnMouseDrag(Event e) { } public virtual void OnMouseMove(Event e) { } public virtual void OnRender(Event e) { } public virtual void OnKeyDown(Event e) { } public virtual void OnKeyUp(Event e) { } } } #endif
Explanation
- Resynchronizing approach: When detecting a difference in count, forcibly trims the longer list to match the shorter by removing the "extras" at the end.
- This prevents exceptions in
RemoveAtand stops the "abort" logs. - Big warning: This method just masks the desync and silently drops tile references or positions, which can cause visual or logical inconsistencies.
- You must audit your entire codebase to fix why these lists ever diverge!
Next steps to debug permanently:
- Find all code changing either list: adding/removing/clearing.
- Make sure every insertion/deletion updates both lists.
- Consider encapsulating the lists inside
Tilemap3Dto hide direct access. - Use add/remove methods that update both lists together atomically.
If you want, I can help refactor your whole tile management system to properly enforce this.
Let me know!
- User
fix it and show all: [HandleRemoveExistingTile] Detected list size mismatch. instantiatedTiles count = 224, instantiatedTilePositions count = 26. Attempting to resynchronize by trimming longer list. UnityEngine.Debug:LogWarning (object) Fabgrid.Tool:HandleRemoveExistingTile (UnityEngine.GameObject) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:87) Fabgrid.Tool:CreateTileAt (UnityEngine.Vector3) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:69) Fabgrid.Brush:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/Tools/Brush.cs:33) Fabgrid.Paint:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:602) Fabgrid.EventHandler:ProcessEvents (UnityEngine.Event,Fabgrid.Tool) (at Assets/Fabgrid/Scripts/Editor/EventHandler.cs:38) Fabgrid.Paint:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:294) Fabgrid.FSM:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/FSM.cs:19) Fabgrid.Tilemap3DEditor:OnDuringSceneGUI (UnityEditor.SceneView) (at Assets/Fabgrid/Scripts/Editor/Tilemap3DEditor.cs:139) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Trimming instantiatedTiles list from 224 to 26 items. UnityEngine.Debug:LogWarning (object) Fabgrid.Tool:HandleRemoveExistingTile (UnityEngine.GameObject) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:97) Fabgrid.Tool:CreateTileAt (UnityEngine.Vector3) (at Assets/Fabgrid/Scripts/Editor/Tools/Tool.cs:69) Fabgrid.Brush:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/Tools/Brush.cs:33) Fabgrid.Paint:OnMouseDown (UnityEngine.Event) (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:602) Fabgrid.EventHandler:ProcessEvents (UnityEngine.Event,Fabgrid.Tool) (at Assets/Fabgrid/Scripts/Editor/EventHandler.cs:38) Fabgrid.Paint:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/States/Paint.cs:294) Fabgrid.FSM:OnSceneGUI () (at Assets/Fabgrid/Scripts/Editor/FSM/FSM.cs:19) Fabgrid.Tilemap3DEditor:OnDuringSceneGUI (UnityEditor.SceneView) (at Assets/Fabgrid/Scripts/Editor/Tilemap3DEditor.cs:139) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
- Assistant
The problem is that the two parallel lists (
instantiatedTilesandinstantiatedTilePositions) are grossly out of sync, and trimming the longer list forcibly discards a lot of data, which can lead to lost references and bugs in your tile management.The best fix is to prevent them from getting out of sync in the first place — by ensuring every add and remove operation acts on both lists together. This means restricting direct access and encapsulating additions/removals inside methods that always update both lists atomically.
Here's a full fixed version of your
Toolclass with minimal changes but adding:- Private helper methods to always add/remove tiles and positions together.
- Replace direct list access with those helpers.
- Remove the risky trimming of lists.
- Defensive debug logging on list sizes mismatch, but silently abort removal to avoid corrupting data.
Fixed
Tool.cs#if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Assertions; namespace Fabgrid { public abstract class Tool { protected Tilemap3D tilemap; protected TilePositionCalculator positionCalculator; protected ToolType toolType; private Camera camera; public const float MAX_PLACE_DISTANCE = 140f; protected Tool(Tilemap3D tilemap) { this.tilemap = tilemap; positionCalculator = CreateTilePositionCalculator(); } private TilePositionCalculator CreateTilePositionCalculator() { switch (tilemap.snapOption) { case SnapOption.Adaptive: return new AdaptiveTilePositionCalculator(tilemap); case SnapOption.Floor: return new FloorTilePositionCalculator(tilemap); case SnapOption.Mesh: return new MeshTilePositionCalculator(tilemap); case SnapOption.Grid: return new GridTilePositionCalculator(tilemap); default: return new AdaptiveTilePositionCalculator(tilemap); } } /// <summary> /// Helper: Add tile and position together to keep lists in sync. /// </summary> private void AddTile(GameObject tile) { tilemap.instantiatedTiles.Add(tile); tilemap.instantiatedTilePositions.Add(tile.transform.position); } /// <summary> /// Helper: Remove tile and position together at index. /// </summary> private void RemoveTileAt(int index) { if (index < 0 || index >= tilemap.instantiatedTiles.Count || index >= tilemap.instantiatedTilePositions.Count) { Debug.LogWarning($"RemoveTileAt invalid index {index}"); return; } tilemap.instantiatedTiles.RemoveAt(index); tilemap.instantiatedTilePositions.RemoveAt(index); } public void CreateTileAt(Vector3 position) { if (position.IsInfinity()) return; if (camera == null) camera = Camera.current; if (Vector3.Distance(camera.transform.position, position) > MAX_PLACE_DISTANCE) return; GameObject tile = (GameObject)PrefabUtility.InstantiatePrefab(tilemap.selectedTile.prefab); if (tilemap.selectedLayer != null) tile.transform.SetParent(tilemap.selectedLayer.transform); else tile.transform.SetParent(tilemap.transform); tile.transform.position = position; tile.transform.rotation = tilemap.tileRotation; Undo.RegisterCreatedObjectUndo(tile, "Placed tile"); if (tilemap.replaceExistingTile) HandleRemoveExistingTile(tile); AddTile(tile); } private void HandleRemoveExistingTile(GameObject tile) { int tilesCount = tilemap.instantiatedTiles.Count; int positionsCount = tilemap.instantiatedTilePositions.Count; // Critical: if counts differ, log and skip removal to avoid corrupting lists further if (tilesCount != positionsCount) { Debug.LogError( $"[HandleRemoveExistingTile] List size mismatch: instantiatedTiles={tilesCount} != instantiatedTilePositions={positionsCount}. Removal aborted."); return; } for (int i = tilemap.instantiatedTiles.Count - 1; i >= 0; --i) { GameObject existingTile = tilemap.instantiatedTiles[i]; if (existingTile == null) { RemoveTileAt(i); continue; } if (Vector3.Distance(tile.transform.position, tilemap.instantiatedTilePositions[i]) < 0.001f) { Undo.DestroyObjectImmediate(existingTile); RemoveTileAt(i); } } } // Virtual Input/Event Handlers are unchanged public virtual void OnDestroy() { } public virtual void OnMouseDown(Event e) { } public virtual void OnMouseUp(Event e) { } public virtual void OnMouseDrag(Event e) { } public virtual void OnMouseMove(Event e) { } public virtual void OnRender(Event e) { } public virtual void OnKeyDown(Event e) { } public virtual void OnKeyUp(Event e) { } } } #endif
Summary:
- No trimming! Never force-remove items to resync the lists; this causes hidden data loss.
- Abort removals if lists are out of sync and log error instead.
- Always add and remove through safe methods (
AddTile,RemoveTileAt) that keep both lists in sync. - You must audit and fix elsewhere in your code any places where these lists are modified directly and cause desync.
- Consider making these lists
privateto prevent external unsafe modification.
If you want, I can also help you refactor your
Tilemap3Dclass to fully encapsulate these lists and enforce safe access! Just ask!