unity3d Unity C#:为什么我会收到错误CS1022:键入名称空间定义,或预期的文件结尾,试图通过索引从列表中随机挑选游戏对象?

5kgi1eie  于 2023-01-09  发布在  C#
关注(0)|答案(2)|浏览(324)

我不相信我有任何丢失分号或丢失/双括号,这是我看到别人说的导致这个错误。谢谢阅读。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class Spawner : MonoBehaviour
{
    public float moveX;
    public float moveXIncrease;
    public GameObject greenSquare;
    public GameObject blueSquare;
    public GameObject pinkSquare;
    public GameObject greySquare;
    
    var squareslist = new List<GameObject>{greenSquare, blueSquare, pinkSquare, greySquare};
    
void Start()
     {
        for (int i = 0; i < 5; i++)
        {
            int index = random.Next(squareslist.Count);
            private GameObject objectToSpawn = squareslist[index];
            
            Vector3 newPos = new Vector3(objectToSpawn.transform.position.x + moveX, objectToSpawn.transform.position.y, objectToSpawn.transform.position.z);
            Instantiate(objectToSpawn, newPos, objectToSpawn.transform.rotation);
            moveX = moveX + moveXIncrease;
        }
     }
}

我试图产卵5个不同的随机彩色块旁边的对方。

b09cbbtk

b09cbbtk1#

不能在函数内声明private作用域。
Start()函数中,删除private关键字。将此行更改为...

private GameObject objectToSpawn = squareslist[index];

...到这个...

GameObject objectToSpawn = squareslist[index];

MS文档...
private (C# Reference)

bakd9h0s

bakd9h0s2#

除了@quaabaam给出的答案之外,您不能在类级别的作用域中使用var关键字。
因此,要修复这两个错误:

var squareslist = new List<GameObject>{greenSquare, blueSquare, pinkSquare, greySquare};
    
void Start()
{
    for (int i = 0; i < 5; i++)
    {
        int index = random.Next(squareslist.Count);
        private GameObject objectToSpawn = squareslist[index];
            
        Vector3 newPos = new Vector3(objectToSpawn.transform.position.x + moveX, objectToSpawn.transform.position.y, objectToSpawn.transform.position.z);
        Instantiate(objectToSpawn, newPos, objectToSpawn.transform.rotation);
        moveX = moveX + moveXIncrease;
    }
}

应为:

private List<GameObject> squareslist;
    
void Start()
{
    squareslist = new List<GameObject>{greenSquare, blueSquare, pinkSquare, greySquare};
    for (int i = 0; i < 5; i++)
    {
        var index = random.Next(squareslist.Count);
        var objectToSpawn = squareslist[index]; 
        var newPos = new Vector3(objectToSpawn.transform.position.x + moveX, objectToSpawn.transform.position.y, objectToSpawn.transform.position.z);
        Instantiate(objectToSpawn, newPos, objectToSpawn.transform.rotation);
        moveX += moveXIncrease;
    }
}

现在有另一个问题。预置不存储位置。你试图从预置列表中读取位置不会产生你想要的结果。如果你想设置"产卵点",你可能想添加空的游戏对象到你的场景,并使用那些位置为你的新示例化的游戏对象。但这是另一个问题,与最初的问题无关。

相关问题