Change the UI image using script in unity c#
<p>I want to change the <strong>UI image</strong> in random order. I have a gameobject in <strong>UI(canvas)</strong> containing <strong>Image component</strong> and it has <em>null image</em> initially. I have a script attached to it(gameobject) to change the image on run time.</p>

<pre><code>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&lt;Image&gt; ().sprite = sprite1;
        //gameObject.GetComponent&lt;UnityEngine.UI.Image&gt; ().sprite = sprite1;
         }
       else if(rand==1)
        {
         gameObject.GetComponent&lt;Image&gt; ().sprite = sprite2;
       // gameObject.GetComponent&lt;UnityEngine.UI.Image&gt; ().sprite = sprite2;
         }
       else if(rand==2)
        {
         gameObject.GetComponent&lt;Image&gt; ().sprite = sprite3;
       //gameObject.GetComponent&lt;UnityEngine.UI.Image&gt; ().sprite = sprite3;
         }
   }
}
</code></pre>

<p>I have assigned the public field (sprite1,sprite2,sprite3) in inspector. And I tried the both option as I had commented in code. I did not get an error but also the image did not get change as I want. <strong>During runtime of a program, GameObject(to which the script is attached) has null image source as it was initially.</strong></p>