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.
  2. Dismiss Notice

4.6 UI How to change an added image-sprite in a button

Discussion in 'Scripting' started by pKallv, Jan 6, 2015.

  1. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,122
    I have added an image into a button and is now trying to change that sprite and have problem to grab it.

    newItem is a GameObject as i create the Button's dynamically.

    Button
    - Text
    - Image <<< Added this to the button

    I am trying to do it with:
    Code (CSharp):
    1. newItem.GetComponentInChildren<Image>().sprite = sprt_twoPlayer;
    but can't actually grab the actual image, i get the button background. The result is that the button native image is change meaning that the background get's the sprite. I want my little added image to get the sprite.

    Anyone that could help me with some tips here?
     
    Last edited: Jan 6, 2015
  2. Polymorphik

    Polymorphik

    Joined:
    Jul 25, 2014
    Posts:
    599
    That should work I just tested it myself. I'm not sure if you are repeatedly doing this, if so I suggest you cache the Image reference and the button so you can edit their properties without having to waste CPU time, its small CPU usage but try to save where you can so your game can run as smooth as possible.
     
  3. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,122
    It somewhat works for me as well but it change the Button image, my sprite is on the button but not on the image i have attached to the button.



    The image i want to change is the small figure in the picture (the added image object), not the actual button.