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.

Set uGUI Image Width in code?

Discussion in 'UGUI & TextMesh Pro' started by tango209, Aug 21, 2014.

  1. tango209

    tango209

    Joined:
    Feb 23, 2011
    Posts:
    379
    For the life of me, I can't figure out how to set the width of a UI Image through code. I've looked through the Image and RectTransform interfaces, but I'm not seeing it. Anyone know how?
     
  2. Melang

    Melang

    Joined:
    Mar 30, 2014
    Posts:
    166
    I don't know how to set rectTransform's width programmatically either, it seems to be read-only. Would setting the scale instead work for you?

    Code (csharp):
    1.  
    2. float newscale = 2f;
    3. rectTransform.localScale = new Vector3(newscale, newscale, newscale);
    4.  
     
  3. tango209

    tango209

    Joined:
    Feb 23, 2011
    Posts:
    379
    Yeah, I noticed in the comment it said it was calculated... so I did end up using the localScale and it worked fine for what I was doing.
     
  4. djweinbaum

    djweinbaum

    Joined:
    Nov 3, 2013
    Posts:
    531
    I can't figure out how to change most of the new GUI components through script right now. For instance how the heck do I access the Image component? If we can change the width of the Rect Transform in the editor there should be a way to modify the same property the editor is modifying.

    EDIT - maybe it has something to do with RectTransformUtility
     
    Last edited: Aug 21, 2014
  5. ortin

    ortin

    Joined:
    Jan 13, 2013
    Posts:
    221
    You mustn't use scale with RectTransform if you want to change width/height;
    rectTransform.sizeDelta = new Vector2(width, rectTransform.sizeDelta.y);
     
    Tim-C likes this.
  6. tango209

    tango209

    Joined:
    Feb 23, 2011
    Posts:
    379
    You can get to the Image object by using GetComponent<Image>(). It's just a script, but it lives in the UnityEngine.UI namespace.
     
  7. tango209

    tango209

    Joined:
    Feb 23, 2011
    Posts:
    379
    Thanks ortin. That's a very confusing name.