实例化一系列按钮

时间:2018-03-22 13:19:39

标签: c# unity3d button instantiation

我需要在表格中实例化/创建按钮。我希望所有的按钮都贴上标签然后也是彩色的,但是从我的研究和测试来看,我相信我只能拥有一个或另一个。我喜欢它们在可滚动的表格中。

        public void OnGUI()
{
    //create a window
    GUI.Window(0, windowRect, WindowFunction, "Meeting Request Viewer");
}
public void WindowFunction(int windowID)
{
    //Fetches all user Data
    string[][] userArray = GetComponent<Userdata>().CallDetail();

    string[][] StudentArray = GetComponent<Userdata>().UserSorting(userArray);

    Debug.Log("here");
    //Calls the SortStudentArray method
    string[,] SortedStudentArray = SortStudentList();        

    //Creates a box with a scrolling bar to taverse the y axis
    scrollPosition = GUI.BeginScrollView(new Rect(Screen.width / 6, Screen.height / 6, 350, 250), scrollPosition, new Rect(0, 0, 300, 40 * SortedStudentArray.Length));

    //for each row in the sorted student array
    for (int x = 0; x < SortedStudentArray.Length; x++)
    {
        GameObject StudentButton = Instantiate(GUI.Button(new Rect(0, BSpace, 300, 20), (SortedStudentArray[x, 6])));

        //This keeps the gap between each button consistent
        BSpace = +scrollPosition.height;
    }    

    GUI.EndScrollView();

}

1 个答案:

答案 0 :(得分:1)

可以同时标记和着色按钮。 Unity的 GUI 是立即模式系统,因此您不需要实例化,必须在每次调用GUI.Button之前设置GUI.color *。这是一个例子;

public int ButtonSpacing = 10;
public int ButtonWidth = 80;
public int ButtonHeight = 30;

public string[] Labels = { "Black", "Red", "Green", "Blue" };
public Color[] Colors = { Color.black, Color.red, Color.green, Color.blue };

private void OnGUI ()
{
    var y = ButtonSpacing + ButtonHeight;

    for (var i = 0; i < 4; i++)
    {
        GUI.backgroundColor = Colors[i];
        GUI.Button(new Rect(ButtonSpacing, ButtonSpacing + i * y, ButtonWidth, ButtonHeight), Labels[i]);
    }
}

*实际上有三种方法可以为GUI着色。选项包括GUI.backgroundColorGUI.contentColorGUI.color。有关其用法的更多信息,请参阅GUI文档。