在Unity3d中动态添加gameobject到场景

我正在创建一个场景,我想在其中显示优惠列表。 为了展示报价,我创建了一个带有占位符的预制件,用于我将在运行时获得的报价详细信息。 我在场景中创建了一个占位符,将预制件添加到场景中,但它没有在UI上显示。 OfferHolderClass:

using UnityEngine; using System.Collections; public class OfferHolder : MonoBehaviour { public GameObject localOffer; // Use this for initialization void Start () { GameObject offer = Instantiate(localOffer) as GameObject; offer.GetComponent().Text = "Testing"; offer.transform.parent = this.transform; } // Update is called once per frame void Update () { } } 

我是Unity的新手,我不确定我在这里缺少什么。

 //Drag object prefab to variable in inspector public GameObject spawnObject; //---------------------------------------- 

下面将使用对象Own Transform设置创建GameObject。

  GameObject clone; clone = Instantiate(spawnObject.transform, spawnObject.transform.position, spawnObject.transform.rotation) as GameObject; 

下面将使用对象Parents Transform设置创建GameObject。

  GameObject clone; clone = Instantiate(spawnObject.transform, transform.position, transform.rotation) as GameObject; 

不确定这是否有帮助,但祝你的游戏好运:)

在Unity中,你可以这样做。

  GameObject.Instantiate(prefab,new Vector3(1,1,0),Quaternion.identity); 

另见: http : //docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.html

特别是对于位置 ,它必须在你的相机前面,否则你可能看不到它。

更重要的是,我建议你看看NGUI。 它是一个function强大的GUI系统,带有一些有用的API用于开发。 顺便说一句我无法想象没有这样的东西开发游戏有多难,所以你迟早可能需要它;

有了它,你可以轻松地做到这一点。

 Gameobject go = NGUITools.AddChild(Gameobject Parent, Gameobject Prefab) 

更新:

当我回答这个问题时,NGUI是唯一可用的gui系统,所以我推荐它。 然而,那里有一个官方的Unity UI系统(AKA uGUI),你真的不必使用NGUI,单独留下gui战争仍在继续。

更重要的是,你可能想要进入池系统。 它用于处理大量的游戏对象,如子弹,立方体等。如果你在同一个场景中有数百个特定的游戏对象并且遭受实例化,那么你可能需要一个游泳池。 就个人而言,我尝试过FastPool并且效果很好,实际上所有类型的资产都完全相同。