【问题标题】:Unity Scripting missing definition for a variable and a unassigned local variable c#Unity Scripting缺少变量和未分配局部变量c#的定义
【发布时间】:2016-03-15 04:38:36
【问题描述】:

我对统一和游戏脚本还很陌生,刚开始时遇到问题。

这是我的playstate.cs(我只是粘贴相关的代码行)

using UnityEngine;
using Assets.Code.Interfaces;
using Assets.Code.Scripts;
using System.Collections;  // dicionario
using System.Collections.Generic;  // dicionario

namespace Assets.Code.States

            gametime = (int)Time.timeSinceLevelLoad / 5;                                

            GUI.Box (new Rect (Screen.width - 650, 10, 100, 25), gametime.ToString() );  // GAME TIME HOURS

            float test;

            if (LoadDiagram.diagramaCarga.TryGetValue(gametime, out test)) // Returns true.
            {
                GUI.Box (new Rect (Screen.width - 650, 275, 50, 25),  test.ToString ());
            }

这是我的 LoadDiagram 的存储位置:

using UnityEngine;
using Assets.Code.Interfaces;
using System.Collections;  // dicionario
using System.Collections.Generic;  // dicionario
using System;
namespace Assets.Code.Scripts
{
    public class LoadDiagram 
    {
        public LoadDiagram ()
        {
            Dictionary<int, float> diagramaCarga = new Dictionary<int, float>();

            diagramaCarga.Add(0, 4.2F);
            diagramaCarga.Add(1, 4F);
            diagramaCarga.Add(2, 3.6F);
            diagramaCarga.Add(3, 3.4F);
            diagramaCarga.Add(4, 3.2F);
            diagramaCarga.Add(5, 3F);
        }
    }
}

所以,我有两个错误:

错误 CS0117:Assets.Code.Scripts.LoadDiagram' does not contain a definition fordiagramaCarga'

错误 Assets/Code/States/PlayState.cs(112,87):错误 CS0165:使用未分配的局部变量 `test'

知道发生了什么吗? 提前致谢!

【问题讨论】:

  • diagramaCarga 仅存在于 LoadDiagram() 构造方法的局部范围内(大括号内)。您需要在类范围内为其创建一个公共属性或字段。

标签: c# unity3d scripting


【解决方案1】:

嗯,@cubrr 的评论是正确的,但他没有把它作为答案。

diagramaCarga 仅存在于 LoadDiagram() 构造方法的局部范围内(大括号内)。您需要在类范围内为其创建一个公共属性或字段。

更具体地说,您正在尝试将其作为其他类中的 static 字段进行访问,这意味着您需要 LoadDiagram 类看起来像这样:

public class LoadDiagram 
{
    public static Dictionary<int, float> diagramaCarga = new Dictionary<int, float>();
    // this is a "static block" which acts like a constructor for static objects,
    // as static classes do not use constructors.
    // If I got the syntax correct, I've never actually used one of these.
    static LoadDiagram(){ // !!edited this line!!
        diagramaCarga.Add(0, 4.2F);
        diagramaCarga.Add(1, 4F);
        diagramaCarga.Add(2, 3.6F);
        diagramaCarga.Add(3, 3.4F);
        diagramaCarga.Add(4, 3.2F);
        diagramaCarga.Add(5, 3F);
    }
}

【讨论】:

  • 所以你删除了这一行: public LoadDiagram () ?它还不起作用我还添加了 2 个额外的花括号
  • 我做的还不止这些。
  • 我现在明白了:类、结构或接口成员声明中出现意外符号 `('
  • 它发生了好几次,字典的每一行一次。
  • *Googles 大约一分钟* 啊,我有一些不正确的语法,检查编辑的答案。只改变了一行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 2015-09-25
  • 2016-01-10
  • 2010-11-17
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多