Unity Array技巧之快速构建0011,000111形式数组
1、Mathf.FloorToInt:
1)功能简述
public static int FloorToInt(float f);
Returns the largest integer smaller to or equal to f.
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));
}
}
1、打开Unity,新建一个空工程,具体如下图
2、在工程中,新建一个脚本“ArrayTest”,双击脚本或者右键“Open C# Project”打开脚本,具体如下图
3、在“ArrayTest”脚本上编写代码,首先设置相关变量,然后使用for循环FloorToInt(i/num)实现0011,000111形式的数组,再在Update分别按下“A、S、D”键,打印结果,具体代码和代码说明如下图
4、“ArrayTest”脚本具体内容如下:
using UnityEngine;
public class ArrayTest : MonoBehaviour {
public int num = 2;
public int length = 12;
private int[] intArray = new int[12];
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.A)) {
//结果{001122334455}
intArray = CreateArray (intArray, 2);
for(int i=0;i < intArray.Length; i++){
print ("intArray [" + i + "]" + intArray [i]);
}
}
if (Input.GetKeyDown (KeyCode.S)) {
//结果{000111222333}
intArray = CreateArray (intArray, 3);
for(int i=0;i < intArray.Length; i++){
print ("intArray [" + i + "]" + intArray [i]);
}
}
if (Input.GetKeyDown (KeyCode.D)) {
//结果{000011112222}
intArray = CreateArray (intArray, 4);
for(int i=0;i < intArray.Length; i++){
print ("intArray [" + i + "]" + intArray [i]);
}
}
}
private int[] CreateArray(int[] _array, int _num){
for(int i=0;i < _array.Length; i++){
_array [i] = Mathf.FloorToInt (i / _num);
}
return _array;
}
}
5、脚本编译正确,回到Unity界面,在场景中新建一个“GameObject”,把“ArrayTest”脚本赋给“GameObject”,具体如下图
6、运行场景,分别按下“A”、“S”和“D”,在控制台Console打印的结果与预期一致,具体如下图