What is better ... Arrays or Enum?

Hi…

what is better to declare vars for various similar objects (in performance case)?

Array:

var tree = Array(3);

function Start(){
tree[0] = GameObject.Find("bark");
tree[1] = GameObject.Find("root");
tree[2] = GameObject.Find("apple");
}

or Enum :

enum Tree{
Bark = 0,
Root = 1,
Apple = 2,
}

private var _tree : Tree;

function Start(){
_tree.Bark = GameObject.Find("bark");
_tree.Root = GameObject.Find("root");
_tree.Apple = GameObject.Find("apple");
}

That’s kind of like asking “which is better, apples or oranges?” Arrays and enums are different and unrelated concepts. Enums are just a way to avoid using “magic numbers”. For example, KeyCodes used with Input are enums. It’s much easier to understand what “Input.GetKeyDown(KeyCode.A)” means instead of “Input.GetKeyDown(97)”. Or an example:

enum Size {Big, Small}
enum Looks {Nice, Pretty, Scary, Ugly}

class Thing {
	var size : Size;
	var looks : Looks;
}

var thing = new Thing();
thing.size = Size.Small;
thing.looks = Looks.Scary;

Enums are actually just ints, and you could use ints instead, like “thing.size = 0; thing.looks = 2;”, but those numbers don’t really tell you anything. It makes your code far more readable to use words instead of a bunch of arbitrary numbers.

Your second code example won’t compile, and isn’t how enums are used. For a collection of similar objects, you use an array. (But don’t use Array…you should use “var trees : GameObject[ ];” instead. If the array needs to be resized, use List: “var trees : List.;”.)

–Eric

1 Like

i see… so i will use GameObject[ ] for elements…
but when i want to extract a script component of those element can i use arrays ?
for instance :

var trees : GameObject[];
var treesScript = Array(2);

function Start(){
treesScript[0] = trees[0].GetComponent("script1");
treesScript[1] = trees[1].GetComponent("script2");

treesScript[0].Earthquake();
}

taking in mind that all my objects have scripts attached to it… (because i’m accessing them from a manager script)

Thanks !

Yes, an object that’s part of an array is no different than if it were not in an array.

–Eric

hey thank you !..