stride3d/stride · error · ArgumentNullException

Cannot add null instance of VirtualButton

Error message

Cannot add null instance of VirtualButton

What it means

VirtualButtonGroup.SetItem validates items replaced at an index and throws ArgumentNullException when the replacement item is null. Like InsertItem, it keeps the group free of null bindings so button matching stays well-defined. The message says 'add' but the operation is an index-based set.

Solutions

  1. Assign a valid IVirtualButton instance instead of null.
  2. Remove the item via Remove/RemoveAt instead of setting it to null.
  3. Initialize the button variable before the assignment.

Example fix

// before
group.Buttons[0] = null; // crash
// after
group.Buttons.RemoveAt(0);
Defensive patterns

Strategy: validation

Validate before calling

if (newButton != null)
    group.Buttons[index] = newButton;
else
    group.Buttons.RemoveAt(index);

Type guard

bool CanReplace(IVirtualButton b) => b != null;

Try / catch

try
{
    group.Buttons[index] = newButton;
}
catch (ArgumentNullException)
{
    group.Buttons.RemoveAt(index); // treat null as removal
}

Prevention

When it happens

Trigger: Assigning group[index] = null or an indexer-based edit in a property grid that sets a binding slot to null.

Common situations: Editing bindings in the Game Studio property grid and clearing a slot; programmatic rebinding code that assigns an uninitialized button variable.

Related errors


AI-assisted analysis of stride3d/stride@96fad776d2 (2026-09-14). Data as JSON: /api/errors/10078edad9a72584. Report an issue: GitHub.

Appendix: source

Thrown at sources/engine/Stride.Input/VirtualButton/VirtualButtonGroup.cs:42

        protected override void InsertItem(int index, IVirtualButton item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item", "Cannot set null instance of VirtualButton");
            }

            if (!Contains(item))
            {
                base.InsertItem(index, item);
            }
        }

        protected override void SetItem(int index, IVirtualButton item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item", "Cannot add null instance of VirtualButton");
            }

            if (!Contains(item))
            {
                base.SetItem(index, item);
            }
        }

        /// <summary>
        /// Implements the + operator.
        /// </summary>
        /// <param name="combination">The combination.</param>
        /// <param name="virtualButton">The virtual button.</param>
        /// <returns>The result of the operator.</returns>
        public static VirtualButtonGroup operator +(VirtualButtonGroup combination, IVirtualButton virtualButton)
        {
            combination.Add(virtualButton);
            return combination;

View on GitHub (pinned to 96fad776d2)