Unity-Technologies/UnityCsReference · error · InvalidOperationException

You shouldn't call Cleanup for Editors. Dispose resources…

Error message

You shouldn't call Cleanup for Editors. Dispose resources in Editor.OnDisable

What it means

Editor.Cleanup is the counterpart to Initialize: hidden via EditorBrowsable(Never) and throwing InvalidOperationException. Resource disposal for editors must happen in OnDisable, so calling Cleanup directly is disallowed.

Solutions

  1. Do not call Cleanup; release resources in Editor.OnDisable.
  2. If a container requires explicit teardown, route it to destroy the editor (DestroyImmediate/UnityEngine.Object lifecycle) rather than calling Cleanup.
  3. Exclude Cleanup from any convention-based method invoker.

Example fix

// before
editor.Cleanup(); // InvalidOperationException

// after
// move disposal into OnDisable; do not call Cleanup
Defensive patterns

Strategy: validation

Validate before calling

// Cleanup is intentionally non-functional; do not call it.
// Dispose resources in OnDisable instead.

Prevention

When it happens

Trigger: Explicitly calling editor.Cleanup(), or an auto-disposal/reflection routine that invokes public methods matching a cleanup convention.

Common situations: DI/container frameworks calling a Cleanup/Dispose-like method by convention. Code that pairs an Initialize call with a Cleanup call. Assuming Cleanup frees native resources.

Related errors


AI-assisted analysis of Unity-Technologies/UnityCsReference@225b0fbdb5 (2026-08-13). Data as JSON: /api/errors/599374add562dd10. Report an issue: GitHub.

Appendix: source

Thrown at Editor/Mono/Inspector/Editor.cs:1516

            return true;
        }

        public virtual bool UseDefaultMargins()
        {
            return true;
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public void Initialize(UnityObject[] targets)
        {
            throw new InvalidOperationException("You shouldn't call Initialize for Editors");
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public void Cleanup()
        {
            throw new InvalidOperationException("You shouldn't call Cleanup for Editors. Dispose resources in " +
                "Editor.OnDisable");
        }

        public bool MoveNextTarget()
        {
            referenceTargetIndex++;
            return referenceTargetIndex < targets.Length;
        }

        public void ResetTarget()
        {
            referenceTargetIndex = 0;
        }

        // Implement this method to show a limited inspector for showing tweakable parameters in an Asset Store preview.
        internal virtual void OnAssetStoreInspectorGUI()
        {
        }

View on GitHub (pinned to 225b0fbdb5)