Hello,
I would like to add an icon next to a text inside a button in Unity 5.6 dynamically by the c# script like this:

within my script i have added a text inside a button but for adding an icon i don’t know, how can i do it?My script:
GameObject button = Instantiate(BtnTemplate)as GameObject;
button.GetComponent<ButtonListButton().SetText("Text");
In ButtonListButton script:
public void SetText(string
strText){
tmpStr = strText;
BtnTxt.text = strText;
I instantiate the button dynamically and i want to add icon and text inside a button dynamically too.
Thanks.
Interesting topic.
You can do this :
public class ButtonListButton : MonoBehaviour // or UIBehaviour
{
[SerializeField] Image buttonImage;
public void SetText (string strText, Sprite sprite)
{
buttonImage.sprite = sprite;
tmpStr = strText;
BtnTxt.text = strText;
}
}
The ButtonListButton component would need to reference the Image component you want to change.
You could also create a “table” or images using a Dictionary, so that instead of passing a Sprite, you would only pass an index or key.
Dictionary <string, Sprite> buttonsSprites = new Dictionary <string, Sprite>();
public void SetSprite (string spriteName)
{
buttonImage.sprite = buttonsSprites[spriteName]
}
Dictionaries are not serialisable though, so you’ll have to build it.
You could do that simply using sprites names.