- Home /
Image texture not visible when loaded in script, and button placement wrt image
Hello, in the example below, I have made prefabs for the UI Button and Raw Image, as I didn't find a way to create them otherwise by script. In order to run this example, create a minimal example with only a Canvas and attach the script to the Canvas. This script runs without errors, but I still have two problems:
1) the texture of the image (a photograph) does not appear in the editor; but if I create the RawImage in the editor, I can see it; I guess something must be missing?
2) I have some trouble centering the button and currently the button is not centered. How should I do it better in the script?
Many thanks.
using UnityEngine;
using UnityEngine.UI;
public class Bug3 : MonoBehaviour
{
Canvas canv;
GameObject prefab_button,prefab_image,play;
public void Start() {
prefab_button = Resources.Load("Prefabs/Button") as GameObject;
prefab_image = Resources.Load("Prefabs/RawImage") as GameObject;
Texture2D raw = Resources.Load<Texture2D>("Images/P1450962.JPG");
canv = GameObject.Find("Canvas").GetComponent<Canvas>();
// background image
background=Instantiate(prefab_image,new Vector3(0,0,0),Quaternion.identity);
background.name="Background";
background.GetComponent<RectTransform>().SetParent(
canv.GetComponent<RectTransform>());
background.GetComponent<RawImage>().texture=raw;
background.GetComponent<RectTransform>().position=new Vector3(0,0,0);
background.GetComponent<RectTransform>().sizeDelta
=new Vector2(Display.main.systemWidth,Display.main.systemHeight);
// button 1
play=Instantiate(prefab_button,new Vector3(0,0,0),Quaternion.identity);
play.name="Play";
play.GetComponent<RectTransform>().SetParent(
background.GetComponent<RectTransform>());
play.GetComponentInChildren<Text>().text = "Play";
play.GetComponentInChildren<Text>().fontSize=23;
play.GetComponent<RectTransform>().localScale=new Vector3(1,1,1);
play.GetComponent<RectTransform>().sizeDelta=new Vector2(200,50);
play.GetComponent<RectTransform>().position=new Vector3(-100,-10,0);
}
}
I managed to load the texture and see it with the following code replacement:
byte[] byteArray = File.ReadAllBytes("Assets/Resources/Images/P1450962.JPG"); Texture2D raw = new Texture2D(2,2); raw.LoadImage(byteArray);
but not with Resources.Load.
Your answer
Follow this Question
Related Questions
How to make buttons not clickable 2 Answers
GUIStyle not working on GUI.Button 4 Answers
Custom Editor Button Style like the one in the Hierarchy 0 Answers
Resizing multiple GUI Textures to remain together 0 Answers
How to change buttons' positions 0 Answers