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. Dismiss Notice

Change sprite via script?

Discussion in 'UGUI & TextMesh Pro' started by FirebladeBR, Sep 19, 2014.

  1. FirebladeBR

    FirebladeBR

    Joined:
    Apr 21, 2014
    Posts:
    65
    Hi, I have been trying everything to change the sprite from an UI image im my scene, but I really don't understand what's wrong with my code:

    Code (JavaScript):
    1.  
    2. var testsprite : Sprite = Resources.Load("testimage", Sprite);
    3. GameObject.Find ("TestImage").GetComponent("Image").sprite = testsprite;
    But I get the following error:

    BCE0019: 'sprite' is not a member of 'UnityEngine.Component'.

    Thanks
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    Never use strings in GetComponent. Also it's better not to use Resources.Load for sprites because they won't auto-batch (if you have Pro).

    --Eric
     
  3. FirebladeBR

    FirebladeBR

    Joined:
    Apr 21, 2014
    Posts:
    65
    Hi Eric,

    Following your instructions I removed the quotes, and the error stoped. But now it is not showing the image. I used this code:

    Code (JavaScript):
    1.  
    2.  
    3. var testsprite : Sprite = Resources.Load("testimage", Sprite);
    4. Debug.Log(testsprite);
    5. GameObject.Find ("TestImage").GetComponent("Image").sprite = testsprite;
    6.  
    7.  
    I still don't have the pro version is this the reason? The log shows: Null

    Thanks for your help
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    Code (javascript):
    1. var testsprite : Sprite; // Assign in the inspector
    2.  
    3. function Start () {
    4.     GameObject.Find ("TestImage").GetComponent(Image).sprite = testsprite;
    5. }
    --Eric