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

Loading Button Image from script

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

  1. FirebladeBR

    FirebladeBR

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

    I created a button from script with the code bellow:

    Code (JavaScript):
    1.         var buttonObject = new GameObject("Button");
    2.         var image = buttonObject.AddComponent(Image);
    3.         image.transform.parent = canvas.transform;
    4.         image.rectTransform.sizeDelta = new Vector2(180, 30);
    5.         image.rectTransform.anchoredPosition = Vector3(0 ,0,0) ;
    6.         image.color = new Color(1f, .3f, .3f, .5f);
    It's creating it perfectly But when I try to change the source image from the image component it is not working. Here's what I tried:

    Code (JavaScript):
    1. image.sprite = Resources.Load("GUISprite", Sprite);
    How can I solve this?

    Thanks!
     
  2. AntFitch

    AntFitch

    Joined:
    Jan 31, 2012
    Posts:
    243
    I would also like to know how to do this. How do we actually change Source Image via script?
     
  3. comixplay

    comixplay

    Joined:
    Sep 27, 2013
    Posts:
    104
    Try this line instead:
    image.sprite = Resources.Load<Sprite>("YourSpriteName");
     
  4. FirebladeBR

    FirebladeBR

    Joined:
    Apr 21, 2014
    Posts:
    65
    Not Working. I think this syntax is for Csharp? right? I'm using JS....

    Detailed Error bellow:

    BCE0051: Operator '<' cannot be used with a left hand side of type 'function(String): UnityEngine.Object' and a right hand side of type 'System.Type'.
     
  5. comixplay

    comixplay

    Joined:
    Sep 27, 2013
    Posts:
    104
    Yep it's in C#,
    sorry... not sure about JS