ero ero - 6 months ago 98
C# Question

Change the UI image using script in unity c#

I want to change the UI image in random order. I have a gameobject in UI(canvas) containing Image component and it has null image initially. I have a script attached to it(gameobject) to change the image on run time.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class changeImg : MonoBehaviour {

public Sprite sprite1;
public Sprite sprite2;
public Sprite sprite3;

void Start()
void ChangeImg()
int rand=Random.Range(0,3);
gameObject.GetComponent<Image> ().sprite = sprite1;
//gameObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite1;
else if(rand==1)
gameObject.GetComponent<Image> ().sprite = sprite2;
// gameObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite2;
else if(rand==2)
gameObject.GetComponent<Image> ().sprite = sprite3;
//gameObject.GetComponent<UnityEngine.UI.Image> ().sprite = sprite3;

I have assigned the public field (sprite1,sprite2,sprite3) in inspector. And I tried the both option as I had commented in code. I did not get an error but also the image did not get change as I want. During runtime of a program, GameObject(to which the script is attached) has null image source as it was initially.


Use overrideSprite field instead of sprite - documentation

Unfortunately, unity ui is full of such pitfalls and it's api is totally counter-intuitive, so you have to be careful and check the docs regularly