I want to change the UI image in random order. I have a gameobject in UI(canvas) containing Image component and it has nul
To change the Image
from a Button
, don't use GetComponent
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.