【问题标题】:Array of ints - does not exist in the current context整数数组 - 当前上下文中不存在
【发布时间】:2020-01-06 15:20:06
【问题描述】:

我尝试创建一个整数数组:

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/) 中代码运行良好。

【问题讨论】:

  • 该代码不会在任何普通的 C# 编译器中都能正常工作。您的第二个语句不是声明,因此应该是方法、构造函数或其他函数成员的一部分。
  • 无法复制:dotnetfiddle.net/S6hZje。您问题中的代码不能与您放入 dotnetfiddle 的代码相同。
  • 我假设您将这些行放在在线编译器的 Main 方法中,这很好,但在这里它们不是在产生所有差异的方法中。
  • @juharr,是的,你是对的。我不知道我不能这样声明。
  • @ExConfessor I didn't know I can't declare it this way 你的声明不是问题。 int[] levelsSolvedCounter = new int[3]; 是一个声明,在类级别是允许的。 levelsSolvedCounter[0] = 10;不是声明,它是声明,不能存在于类级别。

标签: c# arrays unity3d


【解决方案1】:

您不能在类的顶层编写实现。你需要先定义一个方法。

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;
    }
}

【讨论】:

    【解决方案2】:

    这应该可以正常工作:

    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 方法,该方法被执行以更新每一帧的游戏对象状态。我将数据成员保留在方法之外,因此不会在每个帧上一次又一次地创建它。

    【讨论】:

    • Start 会是比 Update IMO 更好的选择,但它并没有错。
    猜你喜欢
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2012-03-21
    相关资源
    最近更新 更多