unity3d - Change the UI image using script in unity c# -
i want change ui image in random order. have gameobject in ui(canvas) containing image component , has null image initially. have script attached it(gameobject) change 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() { changeimg(); } void changeimg() { int rand=random.range(0,3); if(rand==0) { 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 public field (sprite1,sprite2,sprite3) in inspector. , tried both option had commented in code. did not error image did not change want. during runtime of program, gameobject(to script attached) has null image source initially.
use overridesprite
field instead of sprite
- documentation
unfortunately, unity ui full of such pitfalls , it's api totally counter-intuitive, have careful , check docs regularly
Comments
Post a Comment