Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Bug An exception occurs in IndexedSet.ToList

Discussion in 'UGUI & TextMesh Pro' started by Takaaki-Hoshiyama, Oct 16, 2022.

  1. Takaaki-Hoshiyama


    Apr 6, 2014

    I write this code.

    var canvasGraphics = GraphicRegistry.GetRaycastableGraphicsForCanvas(_canvas).ToList();

    This code works fine the first time.
    But when, destroy some parts of the UI, An exception occurs.

    System.Collections.Generic.List`1[T].CopyTo (T[] array, System.Int32 arrayIndex) (at <c2a97e0383e8404c9fc0ae19d58f57f1>:0)
    UnityEngine.UI.Collections.IndexedSet`1[T].CopyTo (T[] array, System.Int32 arrayIndex) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/SpecializedCollections/IndexedSet.cs:121)
    System.Collections.Generic.List`1[T]..ctor (System.Collections.Generic.IEnumerable`1[T] collection) (at <c2a97e0383e8404c9fc0ae19d58f57f1>:0)
    System.Linq.Enumerable.ToList[TSource] (System.Collections.Generic.IEnumerable`1[T] source) (at <93223d662c2546d4b5d1784737504095>:0)
    SRD.Utils.SRDGraphicRaycaster.Raycast (UnityEngine.EventSystems.PointerEventData eventData, System.Collections.Generic.List`1[T] resultAppendList) (at Assets/SRDisplayUnityPlugin/Runtime/Utils/SRDGraphicRaycaster.cs:85)

    This is because you are trying to copy the empty part of m_List as well.
    However, the allocated array is only for m_EnabledObjectCount, so the capacity is not enough.

    I am getting around the exception with the source code below.

    var tempCanvasGraphics = GraphicRegistry.GetRaycastableGraphicsForCanvas(_canvas);
    if(tempCanvasGraphics == null || tempCanvasGraphics.Count == 0)
    var canvasGraphics = new Graphic[tempCanvasGraphics.Count];
    for (var i = 0; i < tempCanvasGraphics.Count; i++)
    canvasGraphics[i] = tempCanvasGraphics[i];