ClaudioA
ClaudioA

Reputation: 317

Unity Scripting missing definition for a variable and a unassigned local variable c#

I am fairly new to unity and game scripting and I am having problems starting out.

This is my playstate.cs (I am only pasting the relevant code lines)

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

And this is where my LoadDiagram is stored:

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

So, I have two errors:

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

error Assets/Code/States/PlayState.cs(112,87): error CS0165: Use of unassigned local variable `test'

Have any idea of what is going on? Thanks in advance!

Upvotes: 0

Views: 167

Answers (1)

Well, @cubrr's comment is correct, but he didn't put it as an answer.

diagramaCarga only exists inside the local scope (inside the curly braces) of the LoadDiagram() constructor method. You need create a public property or field for it inside the class scope.

More specifically, you are trying to access it as a static field inside your other class, which means you would need the LoadDiagram class to look like this:

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

Upvotes: 1

Related Questions