Unity Scripting缺少变量的定义和未分配的局部变量c#

时间:2015-12-09 18:51:01

标签: c# unity3d scripting

我对团结和游戏脚本相当陌生,我在开始时遇到了问题。

这是我的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 for diagramaCarga&#39;

错误资产/代码/状态/ PlayState.cs(112,87):错误CS0165:使用未分配的局部变量`test&#39;

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

1 个答案:

答案 0 :(得分: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);
    }
}