英文:
Array of ints - does not exist in the current context
问题
我尝试创建一个整数数组:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
int[] levelsSolvedCounter = new int[3];
levelsSolvedCounter[0] = 10;
}
但是我收到一个错误消息:
当前上下文中不存在名称 'levelsSolvedCounter'
尽管在在线编译器(https://dotnetfiddle.net/)中,该代码可以正常工作。
英文:
I try to make an array of ints:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
int[] levelsSolvedCounter = new int[3];
levelsSolvedCounter[0] = 10;
}
But I get an error:
> The name 'levelsSolvedCounter' does not exist in the current context
Although in online compiler (https://dotnetfiddle.net/) the code works just fine.
答案1
得分: 4
不允许在类的顶层编写实现代码。您需要首先定义一个方法。
levelsSolvedCounter[0] = 10;
是实现代码。因此,您需要将其定义在一个方法内。
您可以尝试以下方式:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
int[] levelsSolvedCounter = new int[3];
void Update()
{
levelsSolvedCounter[0] = 10;
}
}
英文:
You're not allowed to write implementation on the top-level of a class. You need to define a method first.
The levelsSolvedCounter[0] = 10;
is implementation. So you need to define it within a method.
You could try something like:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
int[] levelsSolvedCounter = new int[3];
void Update()
{
levelsSolvedCounter[0] = 10;
}
}
答案2
得分: 3
这段代码应该可以正常工作:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
int[] levelsSolvedCounter = new int[3];
void Update()
{
levelsSolvedCounter[0] = 10;
}
}
在C#中,所有的逻辑都必须是方法/属性等的一部分,不能直接在类级别上。只有数据字段和其他类成员可以这样做。因此,虽然int[] levelsSolvedCounter = new int[3];
实际上是一个有效的类私有数据成员定义,但levelSolvedCounter[0] = 10;
是无效的,必须在方法内部。在这种情况下,我使用了Update
方法,这是在每帧上更新游戏对象状态的方法。我将数据成员放在方法外部,这样它不会在每一帧中都被重复创建。
英文:
This should work just fine:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
int[] levelsSolvedCounter = new int[3];
void Update()
{
levelsSolvedCounter[0] = 10;
}
}
In C#, all logic needs to be part of a method/property/etc., it cannot be directly on the class level. Only data fields and other class members can. So while int[] levelsSolvedCounter = new int[3];
is actually a valid class private data member definition, the levelSolvedCounter[0] = 10;
is invalid and must be inside a method. In this case I used the Update
method, which is what gets executed to update the game object state on each frame. I kept the data member outside of the method, so it is not created on each frame again and again.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论