Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity UI add Image programmatically

I use the following code to add an image to the canvas however the image is located at the left-bottom corner I want the image to locate at the canvas's center anyone can help me

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestController : MonoBehaviour {

    public GameObject canvas;
    //public Sprite refSprite;

    // Use this for initialization
    void Start () {

        GameObject imgObject = new GameObject("testAAA");

        RectTransform trans = imgObject.AddComponent<RectTransform>();
        trans.anchoredPosition = new Vector2(0.5f, 0.5f);
        trans.localPosition = new Vector3(0, 0, 0);
        trans.position = new Vector3(0, 0, 0);


        Image image = imgObject.AddComponent<Image>();
        Texture2D tex = Resources.Load<Texture2D>("red");
        image.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
        imgObject.transform.SetParent(canvas.transform);


    }

    // Update is called once per frame
    void Update () {

    }
}
like image 258
BPS1945 Avatar asked Oct 20 '25 09:10

BPS1945


1 Answers

You must set parent first and then set position/rotation/scale!

void Start () {
    GameObject imgObject = new GameObject("testAAA");

    RectTransform trans = imgObject.AddComponent<RectTransform>();
    trans.transform.SetParent(canvas.transform); // setting parent
    trans.localScale = Vector3.one;
    trans.anchoredPosition = new Vector2(0f, 0f); // setting position, will be on center
    trans.sizeDelta= new Vector2(150, 200); // custom size

    Image image = imgObject.AddComponent<Image>();
    Texture2D tex = Resources.Load<Texture2D>("red");
    image.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
    imgObject.transform.SetParent(canvas.transform);
}
like image 172
nipercop Avatar answered Oct 22 '25 05:10

nipercop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!