uGUI - assign Image source image at runtime

How do you assign a source image at runtime (how do you call the image ui element…)

Here is an example code for simply replacing the image to another one assigned in editor, but you can obviously get it some other way.

    using UnityEngine;
    using UnityEngine.UI;
    
    public class SpriteReplace : MonoBehaviour
    {
    
        [SerializeField]
        private Sprite sprite = null;   // Assigned in editor
    
        // Use this for initialization
        void Start()
        {
            gameObject.GetComponent<Image>().sprite = sprite;
        }
    }

Here the way I did it with uGUI.

gameObject.GetComponent().image.sprite = YourSprite;

you need to write

using UnityEngine.UI;

at the top of your script, then create an Image component. It has a sprite component, which you can than assign.

Hope this helps

gameObject.GetComponent.().sprite=YourSprite;

    //First Example lack "." before <Image>
    //eg.
    //gameObject.GetComponent.<Image>().sprite= Resources.Load("img/test/short/short_run_right",typeof(Sprite)) ;