I have an array that is supposed to be initializing, but it isn't. In the Start method, I have Code (csharp): priorityNumber = new bool[7]; , but for some reason, when I start the game, the array still says it's of size zero and the script crashes. I share this script between the player character and enemy character and the Player does get the 7 bool sized array. Just none of the enemies do. I will also note that this has worked for a long time now (I wrote that code like a month ago) and only recently stopped working. I'm trying to figure out why it wouldn't work for the enemy, but would for the player since the Start code should get initialized before anything else, so it can't be something deeper into the code right? This kind of boggles my mind. I almost feel like it's a Unity bug, but I won't go as far as coming to that conclusion just yet. Any tips?
Hey, I think it is supposed to be... Code (csharp): // this works private var priorityNumber = new boolean[7]; // this is better IMO private var priorityNumber: Array = new boolean[7]; There could be other ways too...
I use C#, so my way was correct. There were no syntax errors. I did do something different... I moved the array to the very first spot on my list of ~15 lines of code in the Start Method. That made it work lol. No idea why that mattered, especially in that small of an initializer, but it did. I will keep yield in mind if something like that happens again. I didn't think to use that one.
It's an atomic operation; there is no waiting involved. Sounds to me like you initialize it in Start, and are using it in some other script's Start, but the order in which Start runs is undefined. So sometimes it works and sometimes it doesn't. Initialize it in Awake instead, then it's guaranteed to be run before any other Starts are run. --Eric
I've seen this also, and I'm pretty sure I wasn't using this in another script. I had something like this: Dictionary<string, transform> m_TransformsByName = new Dictionary<string, transform>(); void Start() { do stuff; } The dictionary was private, I wasn't using it anywhere...I'm pretty sure, but I don't have the code in front of me. I ended up having to initialize the dictionary in the local Start method. If this is the case, seems like this is potentially a big issue.
Sorry to revive an old thread, but I'm having the exact same issue as jc_lvngstn. I have a Dictionary that is declared and initialised in a MonoBehavior: Code (CSharp): public Dictionary<string, int> valuesDictionary = new Dictionary<string, int>(); But when I try and use it in that Monobehavior, it tells me that it is not set to an instance of an object, and Debug.Logs out 'Null'. I tried setting it to private to test if that was the issue, but I got the same result. The class was working fine before I changed to derive from Monobehavior.
Are you by any chance creating instances of this class using regular constructor mechanisms rather than GameObject.AddComponent?