随机自动生成的 C# 编码问题

C# Coding Issue with Randomized Auto Spawns

我在使用 C# Unity/MonoDevelop 编码时遇到了一些问题。我想要做的是有 30 个不同的位置,但是使用随机化器只有 20 个这些位置会产生一个预制件。我正在使用 Youtube Channel Gamad 关于生成对象的教程 (https://www.youtube.com/watch?v=kTvBRkPTvRY) 修改脚本。 以下是我目前拥有的: `使用 System.Collections; 使用 System.Collections.通用; 使用 UnityEngine;

public class SpawnObject : MonoBehaviour { public GameObject BeehivePrefab;

public Vector3 center;
public Vector3 size;

public Quaternion min;
public Quaternion max;

public int spawnCount = 0;
public int maxSpawns = 20;
public GameObject [] selectorArr;

// Use this for initialization
void Start () {
    SpawnBeehive ();
}

// Update is called once per frame
void Update () {
    while (spawnCount < maxSpawns){
        int temp = Random.Range(0, selectorArr.length);
        selectorArr[temp].Instantiate;
        spawnCount++;
    }
}

public void SpawnBeehive(){
    Vector3 pos = center + new Vector3 (Random.Range (-size.x / 2, size.x / 2),Random.Range (-size.y / 2, size.y / 2), Random.Range (-size.z / 2, size.z / 2));

    Instantiate (BeehivePrefab, pos, Quaternion.identity);
}

void OnDrawGizmosSelected(){
    Gizmos.color = new Color (1, 0, 0, 0.5f);
    Gizmos.DrawCube (transform.localPosition + center, size);
}

}` 在此代码中,我在第 26 行和第 27 行(带有 int tem 和 selectorArr 的行)出现错误。

我以前从未使用过GameObject.Instantiate函数,我通常只是实例化对象或通过代码更改对象的渲染。但是从文档页面 docs.unity3d.com/ScriptReference/Object.Instantiate.html 看来可以让你克隆一个对象

我对你的 GameObject Array selectorArr 有什么用感到有点困惑。

现在,如果它是您想要生成的不同对象的数组,您可以使用类似的方法来完成。

Instantiate(selectorArr[temp], Vector3, Quaternion.identity);

或者,如果您想将随机数保留在一个区域内,您可以通过类似这样的方式重新使用该函数,只需调用 SpawnBeehive( WhatEverGameObjectYouWant )

public void SpawnBeehive(GameObject foobar){
    Vector3 pos = center + new Vector3 (Random.Range (-size.x / 2, size.x / 2),Random.Range (-size.y / 2, size.y / 2), Random.Range (-size.z / 2, size.z / 2));

    Instantiate (foobar, pos, Quaternion.identity);
}