Unity Array技巧之快速构建0011,000111形式数组。本节介绍使用技巧快速构建0011,000111形式的数组,具体如下图
工具/原料
Unity
一、知识要点
1、Mathf.FloorToInt:1)功能简述public 衡痕贤伎static intFloorToInt(floatf);Returns t茑霁酌绡he largest integer smaller to or equal tof.2)使用举例using UnityEngine;using System.Collections;public class ExampleClass : MonoBehaviour { void Example() { Debug.Log(Mathf.FloorToInt(10.0F)); Debug.Log(Mathf.FloorToInt(10.2F)); Debug.Log(Mathf.FloorToInt(10.7F)); Debug.Log(Mathf.FloorToInt(-10.0F)); Debug.Log(Mathf.FloorToInt(-10.2F)); Debug.Log(Mathf.FloorToInt(-10.7F)); }}
二、Array技巧之快速构建0011,000111形式数组
1、打开Unity,新建一个空工程,具体如下图
2、在工程中,新建一个脚本“ArrayTest”,双击脚本或者右键“Open C# Project”打开脚本,具体如下图
3、在“ArrayTest”脚本上编写代码,首先设置相关变量,然后使用for循环FloorToInt(i/num)实现0011,000111形式的数组,再在Update分别按下“A、S、D”键,打印结果,具体代码和代码说明如下图
4、“ArrayTest”脚本短铘辔嗟具体内容如下:usingUnityEngine;publicclassArrayTest:MonoBehaviour{publicintnum=2; publicintlength=12; privateint[]intArray=newint[12];//Updateiscalledonceperframe voidUpdate(){if(Input.GetKeyDown(KeyCode.A)){ //结果{001122334455} intArray=CreateArray(intArray,2); for(inti=0;i<intArray.Length;i++){print("intArray["+i+"]"+intArray[i]); }}if(Input.GetKeyDown(KeyCode.S)){ //结果{000111222333} intArray=CreateArray(intArray,3); for(inti=0;i<intArray.Length;i++){print("intArray["+i+"]"+intArray[i]); }}if(Input.GetKeyDown(KeyCode.D)){ //结果{000011112222} intArray=CreateArray(intArray,4); for(inti=0;i<intArray.Length;i++){print("intArray["+i+"]"+intArray[i]); }} }privateint[]CreateArray(int[]_array,int_num){for(inti=0;i<_array.Length;i++){_array[i]=Mathf.FloorToInt(i/_num); }return_array; }}
5、脚本编译正确,回到Unity界面,在场景中新建一个“GameObject”,把“ArrayTest”脚本赋给“GameObject”,具体如下图
6、运行场景,分别按下“A”、“S”和“D”,在控制台Console打印的结果与预期一致,具体如下图