Search Unity

Bug IndexOutOfRangeException when accessing "Target" on Undo.undoRedoPerformed in Editor

Discussion in 'Scripting' started by Darkgaze, Aug 18, 2021.

  1. Darkgaze

    Darkgaze

    Joined:
    Apr 3, 2017
    Posts:
    395
    On a custom editor


    Code (CSharp):
    1.  
    2.  
    3.     OnEnable()
    4.     {
    5.         Undo.undoRedoPerformed += UndoRedoPerformed;
    6.     }
    7.  
    8.  
    9.       private void UndoRedoPerformed()
    10.         {
    11.  
    12.             try
    13.             {
    14.                 myValue = ((MyClass)target).Property;
    15.             }
    16.             catch (System.IndexOutOfRangeException)
    17.             {
    18.                 return;
    19.             }
    20.         }

    I need to change stuff on my editor when Undo Redo is performed, update some values. But I cannot access the target.

    Even though I get this exception in that exact line inside the try. There is nothing else than this information:

    [Exception] IndexOutOfRangeException: Index was outside the bounds of the array.
    Editor.get_target() at <dc14d30a5e0540ee9311ed6df63d9074>:0

    surprisingly the code inside the Try is executed and "target" contains the target object.
    But I try to execute another line after that one, and the second one is not executed. I guess it's because of the exception.

    Is this a bug? How can I access target without having this exception?
     
  2. Darkgaze

    Darkgaze

    Joined:
    Apr 3, 2017
    Posts:
    395
    Seems like the Target in the Undo callback is not valid anymore due to serialization changes. But if the variable is stored beforehand in the editor (say, in OnEnable), then you can use it to communicate with it.