- Home /
 
Create Unity UI Panel via Script
I want to create a relatively simple UI via C# script only and it should have a simple background rectangle.
For that I created a canvas via C# and want to place some other elements in it.
 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class Test : MonoBehaviour
 {
     private void Awake()
     {
         GameObject obj = new GameObject();
 
         Canvas canvas = obj.AddComponent<Canvas>();
         canvas.renderMode = RenderMode.ScreenSpaceOverlay;
         canvas.pixelPerfect = true;
     }
 }
 
 
               There isn't any class named Panel but instead UnityEngine.UI.Image is used however it cannot be instantiated (protected constructor, WTH?)
What's the best way to create a simple, colored bg rect via script for the Unity UI system?
Answer by prof · Aug 24, 2015 at 11:07 PM
 void Start () {
     GameObject newCanvas = new GameObject("Canvas");
     Canvas c = newCanvas.AddComponent<Canvas>();
     c.renderMode = RenderMode.ScreenSpaceOverlay;
     newCanvas.AddComponent<CanvasScaler>();
     newCanvas.AddComponent<GraphicRaycaster>();
     GameObject panel = new GameObject("Panel");
     panel.AddComponent<CanvasRenderer>();
     Image i = panel.AddComponent<Image>();
     i.color = Color.red;
     panel.transform.SetParent(newCanvas.transform, false);
 }
 
              this gave me a small red square. How do I get it to cover the screen?
Your answer
 
             Follow this Question
Related Questions
UI Canvas Image parented to main camera only moves in x and z 0 Answers
Unity 2D Combat Text Issue With Multiple Enemies 2 Answers
UI - clamp the movement of a panel 0 Answers
Difficulties with world space canvas interaction 1 Answer
UI Minimap 0 Answers