Unity中的数组介绍

数组初始化

string[] arrayA = { "Shirdrn", "Hamtty", "Saxery" };
Console.WriteLine("第一种声明数组并初始化的方法");
string[] arrayB;
arrayB = new string[3] { "shirdrn", "Hamtty", "Saxery" };
Console.WriteLine("第二种声明数组并初始化的方法");
string[] arrayC = new string[3];
arrayC[0] = "Shirdrn";
arrayC[1] = "Hamtty";
arrayC[2] = "Saxery";
Console.WriteLine("第三种声明数组并初始化的方法");

unity中,数组长度可动态指定,即声明数组时,不用指明数组长度,可在inspector中指定数组长度。同时,可利用unity进行数组批量初始化(指定长度为1,赋初值,修改数组长度)

数组遍历

 // for循环遍历数组..
int[] Sum = new int[50];
Random rd = new Random();
// 先用for循环给数组取随机数.
for (int s = 0; s <= Sum.Length - 1; s++)  // Sum.Length是数组的一个属性,Length代表数组的长度
 {
       Sum[s] = rd.Next(100);
 }
  // foreach遍历数组输出
 foreach (int t in Sum)
{
        Console.WriteLine(t);
}

删除元素
(1)for循环遍历

for(int i=0;i<5;i++)

{

 demo[i]=0;

}

(2)重新分配空间

demo = new int[5];

(3)使用Array.Clear

Array.Clear(demo,0,5);

注:使用方法(3)可指定要清除数组的起始位置及要清除的个数;当重新分配空间的次数较少时,(2)方法性能最佳。方法(3)性能较为稳定
数组合并
(1)使用for循环

int []pins = {9,3,7,2}  ;
int []copy = new int[pins.length];  
for(int i =0;i!=copy.length;i++)  
{  
copy[i] = pins[i];  
} 

(2)CopyTo()
语法:public void CopyTo(Array array,int index)
参数:
array:一维数组,它是从当前数组复制的元素的目标。
index:表示 array 中复制开始处的索引。
实例:

int[] pins = { 9, 3, 7, 2 };
int[] copy = new int[pins.Length];
pins.CopyTo(copy, 0);                 //cops:9 3 7 2

int[] pins1 = { 9, 3, 7, 2 };
int[] copy1 = { 0,0,0,0,0,0,0,0 };
 pins.CopyTo(copy1, 1);                 //cops1:0 9 3 7 2 0 0 0

(3)Copy()
语法:public static void Copy(Array sourceArray,Array destinationArray,int length)
参数:
sourceArray:包含要复制的数据的 Array。
destinationArray:接收数据的 Array。
length:一个 32 位整数,它表示要复制的元素数目。
举例:

int[] pins = { 9, 3, 7, 2 };
int[] copy = new int[pins.Length];
Array.Copy(pins, copy, 2);//cops:9 3 0 0

(4)Clone()
语法:public object Clone()
举例:

int []pins = {9,3,7,2};
int []copy4 = (int [])pins.Clone();

二维数组

/ 声明一个锯齿型数组,该数组有两个元素 
int[][] myArray = new int[2][];  
// 其中第一个元素是一个含有五个元素的数组 
// 初始化myArray[0] 
myArray[0] = new int[5] {1,3,5,7,9}; 
// 其中第二个元素是一个含有4个元素的数组 
// 初始化myArray[1] 
myArray[1] = new int[4] {0, 2, 4, 6}; 
// 逐一打印出数组的数组中所有的元素 
for (int i=0; i < myArray.Length; i++)  
{ 
 Console.Write("第({0})个数组: ", i); 
 // 打印一维数组中的元素 
 for (int j=0; j < myArray[i].Length; j++) 
 { 
   Console.Write("{0} ", myArray[i][j]); 
 } 
 Console.WriteLine(); 

版权声明:本文为justtestlike原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。