Search Unity

Why does indexing of sprite-multiple object members begin with 1 instead of 0?

Discussion in 'Scripting' started by mipo, Dec 19, 2014.

  1. mipo

    mipo

    Joined:
    Aug 22, 2013
    Posts:
    19
    I have this sprite sheet split in 20 cells in the Sprite Editor.
    If I do

    stripIcons = Resources.LoadAll("spriteStrip");
    iconSprite = stripIcons[0];
    print(iconSprite);


    I get the "InvalidCastException: Cannot cast from source type to destination type." error.

    If I do instead

    stripIcons = Resources.LoadAll("spriteStrip");
    iconSprite = stripIcons[1];
    print(iconSprite);


    It prints out :

    spriteStrip_0 (UnityEngine.Sprite)

    and all is fine.

    I can access all the members of the sprite sheet, from 1 to 20 instead of the 0-19 I would have expected.
    What is it I don't get about sprite-multiple objects indexing?
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Code (csharp):
    1. function Start () {
    2.     var stripIcons = Resources.LoadAll("SpriteStrip");
    3.     var iconTexture = stripIcons[0];
    4.     print(typeof(iconTexture));
    5.     var iconSprite = stripIcons[1];
    6.     print(typeof(iconSprite));
    7. }
    --Eric
     
  3. mipo

    mipo

    Joined:
    Aug 22, 2013
    Posts:
    19

    Thanx.
    So the first element in that object is a texture and the rest are sprites?!
    Can you point me where in the doc I can have a look at this strange object?
    I can't figure at what point what becomes an array...
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Yes, the first entry is the texture, the rest are sprites. You can't have sprites without a texture. It's not defined anywhere that the first entry is always the texture, though, so it might be best not to take that for granted.

    --Eric
     
  5. BenZed

    BenZed

    Joined:
    May 29, 2014
    Posts:
    524
    In order to disambiguate this, load the resources with a type:

    Code (CSharp):
    1. stripIcons = Resources.LoadAll<Sprite>("spriteStrip");
    2.  
    3. iconSprite = stripIcons[0];