Search Unity

Changing button's image which located inside List

Discussion in 'Scripting' started by FalconJ, Mar 27, 2015.

  1. FalconJ

    FalconJ

    Joined:
    Mar 12, 2015
    Posts:
    146
    I have a list that contains few buttons with different images on each button. how to change one of the button image?
    I know how to call the specific button (using index of course) but doesn't know how to change the image.
    thank you
     
  2. Fajlworks

    Fajlworks

    Joined:
    Sep 8, 2014
    Posts:
    344
    Did you try something like:

    Code (CSharp):
    1. using UnityEngine.UI;
    2.  
    3. List<Button> list;
    4. Image myFancyImage;
    5.  
    6. Button button = list[4];
    7. button.image = myFancyImage;
     
  3. FalconJ

    FalconJ

    Joined:
    Mar 12, 2015
    Posts:
    146
    For that part (myFancyImage), do I need to specify which image is?
     
  4. Fajlworks

    Fajlworks

    Joined:
    Sep 8, 2014
    Posts:
    344
    Yeah, but on second thought maybe you want to do this:

    Code (CSharp):
    1. string myPath = "Images/UI/Button/SciFiButton" //your path in Resources folder
    2.  
    3. Button button = list[4];
    4.  
    5. button.image.mainTexture = Resources.Load<Texture2D>(myPath);
    That way you just replace the texture. I guess that's what your goal is?
     
  5. FalconJ

    FalconJ

    Joined:
    Mar 12, 2015
    Posts:
    146
    I think so. Anyway, can I put those image path into an array?
     
  6. Fajlworks

    Fajlworks

    Joined:
    Sep 8, 2014
    Posts:
    344
    If you intend to have a fixed list of buttons, I suggest you create:

    Code (CSharp):
    1. Texture2D[] textures;   // assign in inspector
    2.  
    3. Button button = list[4];
    4. button.image.mainTexture = textures[1];
    That way you can avoid using strings as path and directly set your texture from inspector.
     
  7. FalconJ

    FalconJ

    Joined:
    Mar 12, 2015
    Posts:
    146
    Unfortunately, the array is randomized, so it can be any button depending on the situation.