Unity3D中可用的数组类型:

来源:互联网 发布:百合蕾丝炫浪网络社区 编辑:程序博客网 时间:2024/06/08 03:02
Built-in array  
Javascript Array  (只有javascript可用)
ArrayList  
Hashtable  
Generic List  
Generic Dictionary  
2D Array
 
1. 内置数组build-in-Array:优点:最高效,唯一能在unity监视面板中看到的数组
缺点:数组成员只能是同一种类型;数组长度不可变,但是可确定数组最大长度,用不到的留空,
尽量用这种数组。
e.g :  
var myArray: int [];//定义一个内置数组,可在面板中决定数组长度并赋值
myArray = new int[10];//新建一个数组并赋值

2. Javascript Array
优点:长度动态调整,成员类型可不同;
缺点:略微消耗资源,只有javascript可用;
e.g:
var myArray = new Array();
3. ArrayList
非常类似于javascript Array,只不过C#中也可用
e.g
var myArrayList = new ArrayList();
4.Hashtable
4.1 哈希表就是键-值的一种映射结构。
4.2 一般来说键是同一种类型,比如字符串,值都是同一种类型,比如GameObject;
一般来说哈希表用在你想要快速访问你的对象时,就像通过名字或身份证号找到某人。和数组不同的是,你必须自己做好键值映射
var h : Hashtable;
h = new Hashtable();
h.add("1","one");
h.add("2","tow");
Debug.Log(h.count);// output 2
5.Generic List
只有在C#中可以使用;非常类似于javascript Array、ArrayList,但是,它的成员只能是同一种类型。
优点:节省资源,不易出错
比较重要的是Generic List不能在iPhone中使用!
c#中使用:必须声明using System.Collections.Generic; 命名空间
List<type> myList = new List<type>();                 // declaration
List<int> someNumbers = new List<int>();              // a real-world example of declaring a List of 'ints'
List<gameobject> enemies = new List<gameobject>();    // a real-world example of declaring a List of 'GameObjects'
6.Generic Dictionary
generic Dictionary 对应 Hashtable, 就像 Generic List 对应ArrayList;是Hashtable的C#版本。
一样只能在C#中使用,必须声明using System.Collections.Generic; 命名空间。不能在iPhone中使用
7.2d Array
最后是有关二维数组的创建和使用
首先明确:只有c#可以创建二维数组,javascript不能创建,但是可以使用,这话怎么这么别扭?没关系,下面有解释
7.1 c# 可以创建 “真”的( myArray[x,y])和“假”的( myArray[x][y])二维数组, 后者其实是一种嵌套结构,所以最好用前一种。但有时2个维度不等长,就只能用假的
 c#创建二维数组举例:
string[,] myArray = new string[16,4];
Tile[,] map = new Tile[32,32]; //制作小地图很有用
7.2 javascript中怎么使用二维数组?
前面说过javascript不能创建,但能使用二维数组,因此我们可以在C#中创建一个2dArray类,然后在javascript中实例化;
举例:
//2dArray in c#
using UnityEngine;  
public class MultiDim : MonoBehaviour
{
  public static int[,] IntArray2D (int x, int y)
 {
         return new int[x,y];
     }
}
保存这个文件在default/script下,然后再建javascript:
var foo = MultiDim.IntArray2D(5, 8);
foo[3,2] = 5;
原创粉丝点击