- Home /
Field Initializer Error
Hello everyone,
I'm working on a project for school and I need to get this complete before I move on. I'm trying to compile a Dictionary listing for animals. For some reason this script is giving me a field initializer error. Any reason why?
using UnityEngine; using System.Collections; // NOTE: To use Dictionary, we must add this line using System.Collections.Generic;
public class ZooRegistry : MonoBehaviour {
int numZebras = zooRegistry["Zebra"];
// variable type variable name
Dictionary<string, int> zooRegistry = new Dictionary<string, int>();
// Key type Value type
// Use this for initialization
void Start () {
zooRegistry.Add ("Zebra", 8);
zooRegistry.Add ("Kangaroo", 2);
zooRegistry.Add ("Giraffe", 6);
zooRegistry.Add ("Penguin", 17);
zooRegistry.Add ("Sea Turtle", 4);
Debug.Log (zooRegistry ["Zebra"]); } // Update is called once per frame void Update() {
}
Answer by Gogeric · Apr 09, 2015 at 05:50 AM
Try that :
public class ZooRegistry : MonoBehaviour {
int numZebras; //You cannot assign this variable with zooRegistry before zoo registry is itself assigned.
// variable type variable name
Dictionary<string, int> zooRegistry = new Dictionary<string, int>();
// Key type Value type
// Use this for initialization
void Start () {
zooRegistry.Add ("Zebra", 8);
numZebras = zooRegistry["Zebra"];
zooRegistry.Add ("Kangaroo", 2);
zooRegistry.Add ("Giraffe", 6);
zooRegistry.Add ("Penguin", 17);
zooRegistry.Add ("Sea Turtle", 4);
Debug.Log (zooRegistry["Zebra"]);
}
// Update is called once per frame
void Update() {
}
The problem is probably that you are trying to access a variable which is not yet initialised and you do that to initialise another variable...
in C# the order matter and moreover the actual error was coming from the fact that you were trying to call a method for an initialisation outside of a method on the class declaration directly, you cannot do that, variables can only be initialised using constants because this type of initialisation is done when the object memory is allocated and filled with the object and no methods can be called here (at least in C#)
Your answer
Follow this Question
Related Questions
GetComponent, What is it ? 1 Answer
Changing Custom Object Variable 1 Answer
UNET Client wont update varsync 0 Answers
Var names in Unity javascript 2 Answers
dictionary of words (as a key) and fbx files (as a value) 1 Answer