统一从数组实例化

Instantiating from an array in unity

我正在尝试实例化存储在数组中的随机小行星游戏对象。但是我遇到了一个错误,无法解决。谁能帮忙:

Assets/Scripts/GameController.cs(7,49): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `GameController.asteroids'

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {

    int asteroids = 2;     
    GameObject[] Asteroids = new GameObject[asteroids];

    public Vector3 spawnValues;
    public int asteroidCount;
    public float spawnWait;
    public float startWait;
    public float waveWait;

    void Start () {

        //call asteroid array variables
        Asteroids [0] = gameObject.tag == "Asteroid01";
        Asteroids [1] = gameObject.tag == "Asteroid02";

        StartCoroutine (spawnWaves ());
    }

    IEnumerator spawnWaves () {

        yield return new WaitForSeconds (startWait);

        while (true) {
            for (int i = 0; i < asteroidCount; i++) {
                Vector3 spawnPosition = new Vector3 (spawnValues.x, Random.Range (-spawnValues.y, spawnValues.y), spawnValues.z);
                Quaternion spawnRotation = Quaternion.identity;

                Instantiate (Random.Range(0,1), spawnPosition, spawnRotation);
                yield return new WaitForSeconds (spawnWait);
            }
        }
    }

编辑:

我一直在玩这个,这是我目前所拥有的:

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {

    public GameObject[] asteroids;
    public Vector3 spawnValues;
    public int asteroidCount;
    public float spawnWait;
    public float startWait;
    public float waveWait;

    void Start () {
        asteroids = GameObject.FindGameObjectsWithTag("Asteroid");
        StartCoroutine (spawnWaves ());
    }

    IEnumerator spawnWaves () {

        while (true) {
            for (int i = 0; i < asteroidCount; i++) {
                Vector3 spawnPosition = new Vector3 (spawnValues.x, Random.Range (-spawnValues.y, spawnValues.y), spawnValues.z);
                Quaternion spawnRotation = Quaternion.identity;
                Instantiate (asteroids[i], spawnPosition, spawnRotation);
                yield return new WaitForSeconds (spawnWait);
            }
        }

这不是实例化游戏对象的正确方法。相反,试试这个:

Instantiate (Asteroids[i], spawnPosition, spawnRotation);

错误是第一个参数是游戏对象,但在您的代码中传递了一个浮点值。同时将您的 new GameObject[asteroids] 代码移动到构造函数或 Start() 方法中,或者尝试使用 constant/static int 值。

您不能使用一个实例变量来初始化另一个实例变量,因为编译器无法保证初始化的顺序。

您可以在构造函数中完成:

public class GameController : MonoBehaviour {

    int asteroids;     
    GameObject[] Asteroids;

    public GameController()
    {
        asteroids = 2;
        Asteroids = new GameObject[asteroids]
    }
...

或者像 cubrr 在评论中所说的那样,小行星可以是一个常数。

您不能以这种方式用普通变量初始化数组。 你可以做

const int asteroids = 2;     
GameObject[] Asteroids = new GameObject[asteroids];

int asteroids = 2;     
GameObject[] Asteroids;

void Start()
{
 Asteroids = new GameObject[asteroids];
}