Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

Feedback [BUG] IndexOutOfRangeException in ResourceManagerConfig.CreateArrayResult

Discussion in 'Addressables' started by phobos2077, Apr 26, 2020.

  1. phobos2077

    phobos2077

    Joined:
    Feb 10, 2018
    Posts:
    350
    Trying to call
    ResourceManager.ProvideResources<Object[]> (locations)
    results in an IndexOutOfRangeException inside ResourceManagerConfig.CreateArrayResult().

    Addressables version: 1.8.3

    Here's the perpetrator's code:

    Code (CSharp):
    1.  
    2.         public static Array CreateArrayResult(Type type, Object[] allAssets)
    3.         {
    4.             var elementType = type.GetElementType();
    5.             if (elementType == null)
    6.                 return null;
    7.             int length = 0;
    8.             foreach (var asset in allAssets)
    9.             {
    10.                 if (asset.GetType() == elementType)
    11.                     length++;
    12.             }
    13.             var array = Array.CreateInstance(elementType, length);
    14.             int index = 0;
    15.  
    16.             foreach (var asset in allAssets)
    17.             {
    18.                 if(elementType.IsAssignableFrom(asset.GetType()))
    19.                     array.SetValue(asset, index++);
    20.             }
    21.  
    22.             return array;
    23.         }
    As you can see, it first checks each element to have the exact type (which will be false obviously, because UnityEngine.Object is not used directly) to determine the array size. Then, when filling the array, it uses IsAssignableFrom which will be true. As a result, it will try to assign an element at index 0 in a 0 size array and fail with the aforementioned exception.

    To fix, first loop needs to be rewritten as follows:
    Code (CSharp):
    1.  
    2.             foreach (var asset in allAssets)
    3.             {
    4.                 if (elementType.IsAssignableFrom(asset.GetType()))
    5.                     length++;
    6.             }
    7.        
     
  2. TreyK-47

    TreyK-47

    Unity Technologies

    Joined:
    Oct 22, 2019
    Posts:
    1,843
    phobos2077 likes this.
  3. phobos2077

    phobos2077

    Joined:
    Feb 10, 2018
    Posts:
    350
    Created case 1243065.