Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Create a button with an image

Discussion in 'UGUI & TextMesh Pro' started by frigatplaygames, Dec 3, 2021.

  1. frigatplaygames

    frigatplaygames

    Joined:
    Dec 3, 2021
    Posts:
    3
    I can create a simple sprite with this code:

    Texture2D texture2D = new Texture2D(2, 2);
    texture2D.LoadImage(File.ReadAllBytes(DevyatInitializer.path + "/Stamina/StaminaTest1.png"));
    Sprite value = Sprite.Create(texture2D, new Rect(0f,0f, (float)texture2D.width, (float)texture2D.height), new Vector2(0.5f, 0.5f));
    GameObject Stamina = new GameObject("New Sprite");
    Stamina.transform.SetParent(this.owner.view.charAppearance.transform);
    Stamina.transform.localScale = new Vector3(0.6f, 0.6f, 0.6f);
    Stamina.transform.localPosition = new Vector3(0.0f, 10f, 0.0f);
    Stamina.layer = LayerMask.NameToLayer("Effect");
    Stamina.SetActive(true);
    SpriteRenderer renderer = Stamina.AddComponent<SpriteRenderer>();
    renderer.sprite = value;

    I tried to create a working button based on the code I already have, but nothing appears:

    Texture2D texture2D = new Texture2D(2, 2);
    texture2D.LoadImage(File.ReadAllBytes(DevyatInitializer.path + "/ArtWork/Shield.png"));
    Sprite value = Sprite.Create(texture2D, new Rect(0f, 0f, (float)texture2D.width, (float)texture2D.height), new Vector2(0.5f, 0.5f));
    GameObject buttonObject = new GameObject("Shield");
    buttonObject.transform.SetParent(this.owner.view.charAppearance.transform);
    buttonObject.transform.localScale = new Vector3(0.6f, 0.6f, 0.6f);
    buttonObject.transform.localPosition = new Vector3(0f, 0f, 0f);
    buttonObject.layer = LayerMask.NameToLayer("Effect");
    buttonObject.GetComponent<Button>().onClick.AddListener(TaskOnClick);
    buttonObject.SetActive(true);
    SpriteRenderer renderer = buttonObject.AddComponent<SpriteRenderer>();
    renderer.sprite = value;

    I probably misunderstood something about the formation of the button object. Can someone help?