将元素添加到通用列表

时间:2013-11-06 11:35:20

标签: unity3d generic-list unityscript

如何向Generic List添加元素?

我在AddAssignment脚本中创建了一个按钮,当我单击它时,我想在分配列表中添加一个元素。添加的元素应该是我的AssignmentClass。

很抱歉,如果需要查看大量代码。

// AddAssignment Script

 #pragma strict
import System.Collections.Generic;

var myTransform : Transform;

var windowOpen : boolean;

var titleText = "title";
var deadlineText = "deadline";
var adressText = "adress";
var cityText = "city";

var baseScript : BaseScript;

function Start () 
{
    myTransform = transform;
    baseScript = myTransform.GetComponent(BaseScript);
}


function Update () 
{
    if (Input.GetKeyUp ("p"))
    {
        windowOpen = !windowOpen;
    }
}


function OnGUI ()
{
    if (windowOpen == true)
    {
        GUI.BeginGroup (new Rect (25, 25, 200, 200));
        GUI.Box (new Rect (0, 0, 200, 175), "");

            //new info
            titleText = GUI.TextField (Rect (25, 25, 100, 25), titleText);
            deadlineText = GUI.TextField (Rect (25, 50, 100, 25), deadlineText);
            adressText = GUI.TextField (Rect (25, 75, 100, 25), adressText);
            cityText = GUI.TextField (Rect (25, 100, 100, 25), cityText);

            //add with new info
            if (GUI.Button (new Rect (25, 130, 150, 25), "Add Assignment"))
            {
                //baseScript.assignments.Add();
            }

        GUI.EndGroup();
    }
}

// BaseScript

#pragma strict
import System.Collections.Generic;

var assignments : List.<Assignments> = new List.<Assignments>();
var scrollPosition : Vector2 = Vector2.zero;


function OnGUI ()
{
    GUI.Box (new Rect (0, 0, Screen.width, Screen.height), "");


    var yOffset = 0;
    for (var i in assignments)
    {

    scrollPosition = GUI.BeginScrollView (Rect (0, 0, Screen.width, Screen.height), 
                            scrollPosition, Rect (0, 0, Screen.width - 25, 75 + yOffset));

        if (GUI.Button (new Rect (Screen.width / 2 - 120, 25 + yOffset, 200, 50), i.title))
        {
            i.running = !i.running;
            Debug.Log(i.title);
        }
        if (GUI.Button (new Rect (Screen.width / 2 + 85, 25 + yOffset, 35, 50), "X"))
        {
            Debug.Log ("removed " + i.title);
            assignments.Remove(i);
        }
        yOffset += 55;

    GUI.EndScrollView ();
    }
}

// AssignmentClass脚本

#pragma strict

class Assignments 
{
    var running : boolean;
    var title : String;
    var deadline : String;
    var adress : String;
    var city : String;
}

1 个答案:

答案 0 :(得分:0)

我自己想出来了。如果有人对我是如何做到这一点感到好奇,那么它就是:我只能在我使用它之前申报我的课程。感觉很蠢:D