Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Getting the right sprite

Discussion in 'Scripting' started by Bloodjoker666, Jan 1, 2022.

  1. Bloodjoker666

    Bloodjoker666

    Joined:
    Nov 26, 2020
    Posts:
    42
    Hi,
    Here what i'm trying to do:

    In Update, I want to change the Image/Sprite of a component like this:

    slot1.GetComponent<Image>().sprite = iconManager.Icon1;

    Now, I want to tell Unity to load the right "iconManager.Icon" number, for example:
    slot2 -> slot2.GetComponent...... = iconManager.Icon2
    slot3 -> slot3...... = iconManager.Icon3
    etc.

    I thouth that I could use a string to set the name like:
    string abc = "iconManager.Icon" + GameManager.slot_id1;
    So, in theory, the string is the name I want to use: iconManager.Icon1
    slot1.GetComponent<Image>().sprite = iconManager.abc;

    Obviously if I use the abc string instead of IconManager.Icon1 it doesn't work.

    How to load "iconManager.IconX" according to the slotY?


    I'm very sorry if my english is bad, or if my query is confused, but thanks!
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,644
    You could just do this simply with some sort of collection, either an Array or a List, and then loop through it.

    Code (CSharp):
    1. List<GameObject> slots = new List<GameObject>();
    2. List<Sprite> icons = new List<Icons>();
    3.  
    4. // populate the lists with your slots and icons
    5.  
    6. for(int i=0; i<slots.Count; i++)
    7.     slots[i].GetComponent<Image>().sprite = icons[i];
     
    Bloodjoker666 likes this.
  3. Bloodjoker666

    Bloodjoker666

    Joined:
    Nov 26, 2020
    Posts:
    42
    Thanks, i'll try that !