Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Updating Images in Canvas Programmatically

Discussion in 'UGUI & TextMesh Pro' started by drac0nic, Jan 17, 2015.

  1. drac0nic

    drac0nic

    Joined:
    Sep 18, 2014
    Posts:
    8
    I've looked through a plethora of tutorials and googled the hell out of this.

    I'm trying to update an image within the canvas programmatically. It is a face and want it change based on actions in the game.

    Maybe i should be using an animation controller but right now i'm just trying to update the image within the component Image(Scripts) within the gameobject under the canvas. Ive got access to the gameobject but i dont know which component to grab in order to change it.

    I just updated to the new unity. I wonder if monoDevelop hasnt updated its database and I'm just not seeing it in the pop up.

    Thanks!
    Scott
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,814
    I just got this working. You create a scene with the Canvas and Image looking like you want, then put this script on the Image object.


    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. using System.Collections;
    5.  
    6. public class Flippy : MonoBehaviour
    7. {
    8. // You load the two images in here...
    9.     public Sprite one;
    10.     public Sprite two;
    11.  
    12.     IEnumerator Start ()
    13.     {
    14.         Image image = gameObject.GetComponent<Image>();
    15.         while( true)
    16.         {
    17.             image.sprite = one;
    18.             yield return new WaitForSeconds( 0.5f);
    19.             image.sprite = two;
    20.             yield return new WaitForSeconds( 0.5f);
    21.         }
    22.     }
    23. }
    24.  
     
    drac0nic likes this.
  3. drac0nic

    drac0nic

    Joined:
    Sep 18, 2014
    Posts:
    8
    Thank you!

    I was missing the package import for UI and would not have guessed to use the sprite variable.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,814
    It seems that setting the import to Sprite is what "applies" the pixels-to-world size (default is 100 pix/world unit) so that the image plays nice inside the RectTransform world.