我需要一些关于以下问题的帮助。我正在制作一个简单的游戏,你有一个角色在奔跑,他必须跳过迎面而来的障碍。
我目前在创建游戏对象并在运行时在游戏场景中随机生成它们时遇到困难。
我编写了一个类来帮助完成此任务:
using UnityEngine;
using System.Collections;
public class randomObstacles : MonoBehaviour {
public GameObject myCube;
public Vector3 spawnLocation = new Vector3(0,2,0);
// Use this for initialization
void Start () {
GameObject SpawnLocation = (GameObject)Instantiate(myCube, spawnLocation, Quaternion.identity);
}
// Update is called once per frame
void Update () {
}
}
上面的代码是我为了简单的一个接一个地创建Object而写的。但是当我运行游戏时,它是空的 -_- !
任何人都可以告诉我哪里出了问题,从它的外观来看,我的代码似乎没有达到我希望实现的目的:(
正如我在 Unity 社区论坛的教程中看到的那样,我已将上述脚本附加到一个空的游戏对象中,但这也无济于事。 (我环顾四周,似乎没有人遇到过这样的问题 - 我可能是错的)
最佳答案
您的 myCube
变量似乎是您问题的根源,已在我自己的场景中对其进行了测试。通过替换
(GameObject)Instantiate(myCube, ...
与
(GameObject)Instantiate(GameObject.CreatePrimitive(PrimitiveType.Cube), ...
我能够毫无顾虑地在 (0,2,0) 处生成一个立方体。也许您的 myCube
游戏对象缺少网格渲染器,在这种情况下,它会在运行时出现在层次结构中,即使它在游戏 View 中不可见。也许您在运行游戏之前没有在 Inspector 中分配它,在这种情况下,myCube
变量将引用 null
,因此不会被创建。此外,虽然您可能将实例化的 GameObject 分配给 SpawnLocation,但它是一个未使用的局部变量(MonoDevelop 或您的代码编辑器应该通知您)。确保您在运行前在 Inspector 中提供对 myCube
游戏对象的引用,或者在运行时通过脚本引用加载的预制件/游戏对象。提供回退(例如,也许是 PrimitiveType.Cube?)也会很有帮助,这将使您的代码更健壮,并且能够在引用错误出现时处理它们。
无论如何,为了实现您所描述的功能,首先请确保您已正确准备好您希望 myCube
成为的任何内容。此外,为了将来的后代,您可能希望在 Start
例程中初始化您的 spawnLocation
,并通过替换 Random.value * yourValueCeiling
来分配变量坐标> 在每个你希望 myCube
生成的随机坐标中。您甚至可以尽可能地使辅助方法外部化,从而独立于启动例程,这样您就不必拥有单个脚本的一百个实例来创建所需内容的一百个实例;相反,您可以通过单个脚本调用该方法,这样可以省去麻烦。如果您不胜感激,这是我对您目标的实现,希望对您有所帮助!
using UnityEngine;
using System.Collections;
public class randomObstacles : MonoBehaviour {
public Vector3 spawnLocation;
public GameObject myCube;
// Use this for initialization
void Start () {
if (myCube != true) {
Debug.Log("myCube not set");
myCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
}
if (myCube.renderer.enabled == false) {
Debug.Log("myCube not rendered");
myCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
}
CreateCube();
}
// Update is called once per frame
void Update () {
}
void CreateCube() {
spawnLocation = new Vector3(0, Random.value * 10, 0);
Instantiate(myCube, spawnLocation, Quaternion.identity);
}
}
关于c# - 如何以编程方式随机生成游戏对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16183457/