Array reporting wrong length!? Is this a bug?

var animals = Array("cat", "dog", "pig", "dolphin", "chimpanzee");
animals.Add("lemur");
var total = animals.length;
Debug.Log(animals + " length is " + total);

On my machine, the length is displayed as 5. It should be 6!

Before filing a bug report, I just wanted someone to proof-read this. I haven’t had my caffeine yet…

FYI, I’m using Unity iPhone 1.5.

It does print 6. Something so basic is highly unlikely to be a bug…whenever I find a “bug” I make sure to exhaust all possibilities to determine that it actually is a bug before filing a report, because it’s usually just something I’m doing wrong, and they don’t need any more bogus “bug” reports than they already get…

–Eric

Yeah, I realize it’s “basic”, but it does appear to be a bug. Did you copy my code EXACTLY and put it in an empty script?

It prints 6 if run under Update(), but 5 if run outside Update().

This is with a new project and no objects other than the main camera (which the script is attached to).

I even tested it with private vars, same result.

Nope, I put it in a Start function. Code outside functions is only supposed to be used for initializing variables.

–Eric

That is the convention, yes.

And I’d follow it if I were working on a game. But for testing purposes, it’s useful to run a few lines of code in an empty script. I’ve never run into a problem doing this until now.

Just put any code in a Start or Awake function…there are a number of problems that result if you don’t; quite lucky if you haven’t run into any before.

–Eric

The why of this bothers me, so I’ll take a stab at what’s happening.

I think internally code outside classes gets expanded into the following prior to full compilation (I normally use C#, so my syntax might be off):

class Blah
{
var animals = Array(“cat”, “dog”, “pig”, “dolphin”, “chimpanzee”);
var total = animals.length;

function PreAwake()
{
animals.Add(“lemur”);
Debug.Log(animals + " length is " + total);
}
}

Variables are made into class variables, while normal code is placed in an internal initializer function that gets called just before Awake.

Does this make sense?

Yes, all external statements in JavaScript, aside from variable declarations, get automatically moved to a Main() function. Main() is called immediately before Start().

I think you can still manually declare it if you want, although it’s undocumented.

Ah, and there’s our definitive answer. Thanks Matthew!