I want to change the UI image in random order. I have a gameobject in UI(canvas) containing Image component and it has nul
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
To change the Image
from a Button
, don't use GetComponent<Image> ()
as you can potentially get another Image
component that does not belong to the button. It can also return null
if the object is disabled.
Use the Button.image.sprite
or Button.image.overrideSprite
variable instead.
public Button pb;
public Sprite newSprite;
void Start()
{
pb.image.sprite = newSprite;
}
Or
pb.image.overrideSprite = newSprite;
It really doesn't matter which one is used. Any of these two should work.
You can also just use Image if you are in Unity 2017.3 (not sure if this works for older versions). For example:
using UnityEngine.UI;
-----
public Image ObjectwithImage;
public Sprite spriteToChangeItTo;
void Start () {
ObjectwithImage.sprite = spriteToChangeItTo;
}
Works great for me.
Have you checked the position of the Gameobject? Also the color of the image?