【发布时间】:2020-01-30 13:19:46
【问题描述】:
我的统一代码有问题,我不明白为什么它不起作用。我对统一有点陌生,刚刚开始学习它。我在项目树中有4个具有不同名称的预制件,我希望每秒生成一个预制件,但我希望它在不使用“if”的情况下随机化,所以我尝试将预制件名称保存在一个数组中然后实例化与数组值同名的 GameObject。当我在 Unity 中运行我的脚本时,它说我要实例化的对象为空,我试图在网上找到答案,但我什么也没找到。你能帮助我吗?
这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawnnoif : MonoBehaviour
{
public GameObject cub;
public GameObject capsula;
public GameObject cilindru;
public GameObject sfera;
public int x;
public GameObject paleta;
public float delta;
public string[] a = { "cub", "capsula", "cilindru", "sfera" };
void Start()
{
Vector3 position = new Vector3(UnityEngine.Random.Range(-1.88f, 2.1f), 1, UnityEngine.Random.Range(-7.81f, -3.1f));
x = UnityEngine.Random.Range(0, 3);
Instantiate(GameObject.Find(a[x]), position, Quaternion.identity);
}
IEnumerator Spawn()
{
while (true)
{
Vector3 position = new Vector3(UnityEngine.Random.Range(-1.88f, 2.1f), 1, UnityEngine.Random.Range(-7.81f, -3.1f));
x = UnityEngine.Random.Range(0, 3);
Instantiate(GameObject.Find(a[x]), position, Quaternion.identity);
yield return new WaitForSeconds(1.0f);
}
}
}
【问题讨论】:
-
你确定
GameObject.Find(a[x])会返回一些东西吗? -
我现在将游戏对象移到场景中,看起来这是个问题,但它仍然只生成立方体,没有生成其他对象
-
所有对象的标签名都正确吗?
-
@krobelusmeetsyndra
Find与标签无关,仅与对象名称有关