Hallo fellow developers
I am busy with a project that requires list boxes, basically my scene will start up a list with text (Buttons) appears on the right hand side and another on the left with a scroll bar attached. When the scene starts up an X amount of buttons will appear on both sides. The scroll bar will move the positions of the buttons up or down ( On the Y axis ) the top/bottom buttons will move out of view from the user.
Here is the code for how I am creating a button at the moment.
float posLeft;
float posTop;
void OnGUI()
{
posLeft = 0;
posTop = 0;
for (int i = 0; i < 5; i++) {
posTop+= +105;
if (GUI.Button (new Rect (posLeft, posTop,100,100), "Button" + i)) {
Debug.Log ("Test");
}
}
}
I can’t find any code on loading scripts onto the button as I create them. The scripts I want to load on the button is to just give them extra functionality (OnPointerEnter/OnPointerExit etc)
Thank you for your time
EDIT: Answer to my question is in this code.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ListBox : MonoBehaviour {
Canvas can;
RectTransform rct;
Image img;
CanvasRenderer cr;
SpriteRenderer spt;
Text butText;
GameObject mygo;
GameObject mygo2;
GameObject mygo3;
float posY = 443;
void Start () {
mygo = GameObject.FindGameObjectWithTag ("canPreset1");
for(int i = 0; i < 18; i++)
{
mygo2 = new GameObject("Button" + i, typeof(Button));
mygo3 = new GameObject("Text" + i, typeof(Text));
mygo2.layer = 5;
mygo2.AddComponent<RectTransform>();
mygo2.AddComponent<Image>();
mygo2.AddComponent<CanvasRenderer>();
mygo2.AddComponent<Sctipt>();
rct = mygo2.GetComponent<RectTransform>();
img = mygo2.GetComponent<Image>();
cr = mygo2.GetComponent<CanvasRenderer>();
rct.position = new Vector3(727,posY,0);
rct.sizeDelta = new Vector2(160,30);
spt = GameObject.FindGameObjectWithTag("sprite").GetComponent<SpriteRenderer>();
img.sprite = spt.sprite;
img.type = Image.Type.Sliced;
mygo3.layer = 5;
butText = mygo3.GetComponent<Text>();
rct = mygo3.GetComponent<RectTransform>();
butText.text = "I was Programmed";
butText.font = GameObject.FindGameObjectWithTag("txtPreset1").GetComponent<Text>().font;
butText.color = Color.black;
rct.position = new Vector3(727 + 5,posY - 5,0);
rct.sizeDelta = new Vector2(150,25);
mygo2.transform.parent = mygo.transform;
mygo3.transform.parent = mygo2.transform;
posY = posY - 25;
}
}
}