【问题标题】:Creating Class instances in Unity at runtime在运行时在 Unity 中创建类实例
【发布时间】:2013-09-27 09:42:24
【问题描述】:

我想循环创建 X 个对象,访问和设置新创建对象的属性。我已经使用 Instantiate 方法和传递的刚体,如教程中所示,但我需要访问连接到对象的脚本的属性,而不仅仅是刚体。

这是我正在尝试的方法:

public void makeGrid(int w = 10, int h = 10)
{
    gridWidth = w;
    gridHeight = h;

    int tileArrayLength = gridWidth * gridHeight;
    tileArray = new Tile[tileArrayLength];

    for (int i = 0; i < gridWidth; i++)
    {
        for (int j = 0; j < gridHeight; j++)
        {
            // add tiles
            Tile t = new Tile(); // !!! doesn't work >_<
            t.posX = i;
            t.posY = j;
            t.id = j + 10 * i;

            tileArray[t.id] = t;
        }
    }

}

【问题讨论】:

    标签: c# oop unity3d


    【解决方案1】:

    我想循环创建 X 个对象,访问并设置 新创建的对象。

    您可以通过编辑器创建预制件然后实例化它们,或者显式创建一个GameObject 并将您需要的组件附加到它:

    GameObject prefabInstance = GameObject.Instantiate(Resource.Load("path_to_prefab")) as GameObject;
    
    GameObject instanceThroughReference = GameObject.Instantiate(aReferenceToAnInstantiableObject) as GameObject;
    
    GameObject emptyGameObject= new GameObject("empty game object");
    

    关心什么:

    我使用了带有传递 RigidBody 的 Instantiate 方法,如图所示 在教程中,但我需要访问脚本的属性 连接到对象,而不仅仅是刚体。

    对于属性,我认为您的意思是 Components 附加到 GameObject 实例化。 如果您从引用实例化对象或通过 Resources.Load 加载,如果原始 GameObject 具有您想要附加的组件,您可以使用 GetComponent 方法检索它们,或者捕获 AddComponent 的返回值。

    如果您要创建一个空的GameObject,则必须明确附加您需要的Components

    GameObject go = new GameObject("foo");
    Bar bar = go.AddComponent<Bar>(); //where Bar extends MonoBehavior
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      相关资源
      最近更新 更多