Unity Create UI Control from Script

how can i dynamically generate a Gui in Unity3D via scripting?

Managed to fix my code.
How I did it:
1. Add an empty gameobject to the editor
2. Add a canvas with a panel as a child
3. Add the following script to the empty gameobject in step 1:

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

public class generateUI : MonoBehaviour
{
public GameObject canvas;
public GameObject Panel;
public GameObject image;
int size = 40;

private float scaler = 0.0125f;
void Start()
{
Panel.transform.SetParent(canvas.transform, false);
GameObject[] tiles = new GameObject[size];
Vector3 change = new Vector3(20 * scaler, 0, 0);
for (int i = 0; i < size; i++)
{
tiles[i] = GameObject.Instantiate(image, transform.position, transform.rotation);

tiles[i].transform.position += change;
tiles[i].transform.SetParent(Panel.transform, false);
}
}
}

4: now add the following script to the canvas object:

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

public class DynamicGrid : MonoBehaviour
{
public int col,row;
void Start()
{
RectTransform parent = gameObject.GetComponent<RectTransform>();
GridLayoutGroup grid = gameObject.GetComponent<GridLayoutGroup>();
grid.cellSize = new Vector2(parent.rect.width / col, parent.rect.height / row);
}
void Update()
{

}
}

5: Set the canvas width to 1090 and height to 430

6: make a prefab from an image(100 by 100)

7: add a Grid Layout Group to the Panel

8: Set CellSize to 100 by 100 and spacing to 10 by 10

9: change the size in the generateUI script to a number you'd like to see

10: profit.

Sample Image

I now have the desired function. I followed @jour's suggestion to use a gridlayout, which I've used before while creating a mobile app with python's Kivy software.

Create UI Button from C# script in Unity 4.6 without any prefabs

The following applies only to the legacy "gui" system from Unity3 (before about 2012). It is now unavailable.

Add this function to any script and it will display 100 x 100 pixel sized button on the left upper corner. Then just change the Debug.Log to your debug code.

void OnGUI() // deprecated, use ordinary .UI now available in Unity
{
if(GUI.Button(new Rect(0, 0, 100, 100), "Debug!")){
Debug.Log("Do some debugging");
}
}

Unity how to Create Texts via script?

You need to create a text object on a new gameobject.

static Text CreateText(Transform parent)
{
var go = new GameObject();
go.transform.parent = parent;
var text = go.AddComponent<Text>();
return text;
}
var mytext = CreateText(LevelCanvas.transform);
myext.text = ...

Adding button with Text dynamically to UI at runtime in Unity

I highly advise you to instantiate a prefab instead of creating the button from scratch.

A gameobject with a RectTransform and button only won't be visible, and won't react to clicks, because you need additionnal components (such as Canvas Renderer and Image / Raw Image).

// Drag & Drop the prefab of the button you will instantiate
public GameObject buttonPrefab ;

public void MakeButton(string direction)
{
// Instantiate (clone) the prefab
GameObject button = (GameObject) Instantiate( buttonPrefab ) ;

var panel = GameObject.Find("CommandPanel");
button.transform.position = panel.transform.position;
button.GetComponent<RectTransform>().SetParent(panel.transform);
button.GetComponent<RectTransform>().SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,0,10);
button.layer = 5;

}

Moreover, you have to be careful to one additional thing : when you ask Unity to create a button (Using GameObject > UI > Button), Unity creates several gameobjects (the button + child) with all the appropriates components (button, canvas renderer, text, ...).

Adding the Button component won't add all the other components and children Unity does. Thus button.GetComponentsInChildren<Text>()[0].text = "New Super Cool Button Text"; won't work (since you haven't added the child and its Text component in your script)

Additional note : Check this link if you have some problems with placing your object : https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html

Generate UI code using unity

Since UI elements are "just" components of GameObjects, yes, you can create them using a script.

But a "better" idea would be to instantiate Prefabs with the components already configured, and you just have to change some values and place your elements.

See the documentation of Unity here about the subject :

https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html



UNITY 5.4

Creating UI elements from scripting

If you are creating a dynamic UI where UI elements appear, disappear, or change based on user actions or other actions in the game, you may need to make a script that instantiates new UI elements based on custom logic.

Creating a prefab of the UI element

In order to be able to easily instantiate UI elements dynamically, the first step is to create a prefab for the type of UI element that you want to be able to instantiate. Set up the UI element the way you want it to look in the Scene, and then drag the element into the Project View to make it into a prefab.

For example, a prefab for a button could be a Game Object with a Image component and a Button component, and a child Game Object with a Text component. Your setup might be different depending on your needs.

You might wonder why we don’t have a API methods to create the various types of controls, including visuals and everything. The reason is that there are an infinite number of way e.g. a button could be setup. Does it use an image, text, or both? Maybe even multiple images? What is the text font, color, font size, and alignment? What sprite or sprites should the image use? By letting you make a prefab and instantiate that, you can set it up exactly the way you want. And if you later want to change the look and feel of your UI you can just change the prefab and then it will be reflected in your UI, including the dynamically created UI.

Instantiating the UI element

Prefabs of UI elements are instantiated as normal using the Instantiate method. When setting the parent of the instantiated UI element, it’s recommended to do it using the Transform.SetParent method with the worldPositionStays parameter set to false.

Positioning the UI element

A UI Element is normally positioned using its Rect Transform. If the UI Element is a child of a Layout Group it will be automatically positioned and the positioning step can be skipped.

When positioning a Rect Transform it’s useful to first determine it has or should have any stretching behavior or not. Stretching behavior happens when the anchorMin and anchorMax properties are not identical.

For a non-stretching Rect Transform, the position is set most easily by setting the anchoredPosition and the sizeDelta properties. The anchoredPosition specifies the position of the pivot relative to the anchors. The sizeDelta is just the same as the size when there’s no stretching.

For a stretching Rect Transform, it can be simpler to set the position using the offsetMin and offsetMax properties. The offsetMin property specifies the corner of the lower left corner of the rect relative to the lower left anchor. The offsetMax property specifies the corner of the upper right corner of the rect relative to the upper right anchor.

Customizing the UI Element

If you are instantiating multiple UI elements dynamically, it’s unlikely that you’ll want them all to look the same and do the same. Whether it’s buttons in a menu, items in an inventory, or something else, you’ll likely want the individual items to have different text or images and to do different things when interacted with.

This is done by getting the various components and changing their properties. See the scripting reference for the Image and Text components, and for how to work with UnityEvents from scripting.

How to change text by script in Unity

Here in Unity, you have a component-oriented design. Text and Button are just Components of GameObject entities. Most parts of your game scripts are also Components that are attached to GameObject. This is a core concept you'd need to realize when you come from JS.

In short, to change a text by clicking the button you need:

1) Create a GameObject with a Text component;
2) Create a GameObject with a Button component;
3) Create a GameObject with a component of your custom script;
4) Create the reference in your custom script on the Text component you want to update;
5) Create a public method in your custom script that will be invoked when you click Button;
6) Assign that method invocation to the OnClick button event through Unity inspector.

Your script will look like this:

    using UnityEngine;
using UnityEngine.UI;

public class ExampleScript : MonoBehaviour
{
[SerializeField]
private Text _title;

public void OnButtonClick()
{
_title.text = "Your new text is here";
}
}

Your scene should look like this. Pay attention to the highlighted Title reference. You need just to drag-n-drop Title GameObject here, and that's it.

a

Select your button, assign a GameObject with your script and select a public method that needs to be invoked

a

Welcome in Unity and happy coding!



Related Topics



Leave a reply



Submit