How to change UI image by c# script in unity with example
Changing a UI image with script in runtime is a quit simple thing. in many case you want to change UI image at runtime so Lets understand it by a simple example.
1. first we need a UI Image GameObject so create a UI Image Object by navigating GameObject > UI > Image or whatever steps you want to create, just create.
2. then create a c# script. and attach it any gameobject you want.
3.to replace a UI image you need refence UI image so declare a Image of name whatever you want and declare sprite for changed sprite reference. I have named Image as original_img and sprite to change as other_img.
4.Drag Image gameObject from hierarchy window to attacched script Image (named original_img) and also drag image sprite from assets folder to script sprite (named as other_img).
4. lets create a change_image() function. you can use this function or inside code to change image where you want. As we have used in start method.
We have used [SerializeField] so that values of that variable can be visible in inspector window for editing without declare public.
Always take care that that you have included "UnityEngine.UI" otherwise you will gets error because images are past of UI.
You can do same thing for changing image of multiple gameObject or to multiple sprites to change by using array. in case of array you can use as follows code