Search Unity

Changing Images Dynamically

Discussion in 'Scripting' started by vladc99, Aug 5, 2020.

  1. vladc99

    vladc99

    Joined:
    Jul 21, 2020
    Posts:
    2
    Hello everyone!

    I'm trying to dynamically change a RawImage
    Here's my code bellow, doesn't seem to work
    Can't find anything online
    I should also add that I'm a new Unity Dev

    Thanks in Advance!

    Code (CSharp):
    1. {
    2.     public RawImage img;
    3.     private string url = "https://i.redd.it/bz504sn6ree51.png";
    4.     //private int imgHeight = 250;
    5.     //private int imgWidth = 250;
    6.     //private int posX = 10;
    7.     //private int posY = 50;
    8.     private int counter = 1;
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         StartCoroutine(ChangeImage());
    14.     }
    15.  
    16.     IEnumerator ChangeImage(){
    17.         yield return 0;
    18.         UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
    19.      
    20.         Debug.Log("Here2, url: "+url);
    21.         yield return www.SendWebRequest();
    22.  
    23.         img.texture = DownloadHandlerTexture.GetContent(www);
    24.      
    25.         // TextureScaler.scale(img.texture,imgHeight,imgWidth);
    26.     }
    27.  
    28.     void Update()
    29.     {
    30.         if(Input.GetKeyDown(KeyCode.Space)){
    31.             if(counter % 2 == 0){
    32.                 url = "https://i.redd.it/bz504sn6ree51.png";
    33.             }else{
    34.                 url = "https://i.redd.it/rgce12mplle51.jpg";
    35.             }
    36.             counter++;
    37.             Debug.Log("Here");
    38.             StartCoroutine(ChangeImage());
    39.         }
    40.     }
    41. }
     
    Last edited: Aug 5, 2020
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    Why are you setting img = null in line 31 above?
     
  3. vladc99

    vladc99

    Joined:
    Jul 21, 2020
    Posts:
    2
    Oh I was trying to reset the image, scratch that