一些函数与功能(不定时更新)
1:byte数组转string输出
byte[] result=new byte[]{1,2,3,4};
string vstr = "{" + string.Join(",", result) + "}";
Debug.Log(vstr);
2:sbyte转byte
sbyte[] temp = new sbyte[]{ 8, -25, 7} ;
byte[] temp2 = new byte[temp.Length];
Buffer.BlockCopy(temp, 0, temp2, 0, temp.Length);
3:在脚本中实例化Button类型预制体并添加onclick()函数
public GameObject car;//设置预制体
GameObject Car = Instantiate(car).gameObject;//实例化
newCar.GetComponent<RectTransform>().SetParent(this.GetComponent<RectTransform>());//设置父节点
Car.GetComponent<Button>().onClick.AddListener(() => { run(); });//添加onclick函数run()
4:判断物体是第几个子物体
int index = this.transform.GetSiblingIndex();
5:依据name寻找子物体
string name = "Car";
GameObject obj = this.transform.Find(name).gameObject;
6:int转string
string name = Convert.ToString(index);
8:image转byte
private byte[] ImageToBytes(string imageFileName){
return File.ReadAllBytes(imageFileName);
}
9:byte[ ] 转 texture
private static Texture2D BytesToImage(byte[] bytes,int w=800,int h=561)
{
Texture2D texture2D = new Texture2D(w, h);
texture2D.LoadImage(bytes);
return texture2D;
}
10:img,byte[ ],sprite
public Image Img;
public Sprite oldSprite;
public Sprite newSprite;
private string imageName;
void Start()
{
imageName = "Assets/Img/" + "斋藤飞鸟.jpg";//原图片地址,jpg格式
Img.sprite = oldSprite;//设置ui的sprite
byte[] x = ImageToBytes(imageName);//图片转byte[]
Debug.Log(x.Length);//用于判断是否转化成功,能输出则表示成功
Texture2D texture2D = BytesToImage(x);//byte[]转texture2D
newSprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero);//根据texture2D设置sprite
Img.sprite=newSprite;//给ui贴图
}
11:当退出程序时,如果要执行一些代码,可以使用OnApplicationQuit(),该函数为unity默认函数
private void OnApplicationQuit()
{
Debug.Log("我在这!!!");
}
12:OnApplicationQuit()函数只能在unity的编辑器条件下使用,如果要导出apk,在安卓环境下运行,需要将OnApplicationQuit()替换为OnApplicationPause()
private void OnApplicationPause()
{
Debug.Log("我在这!!!");
}
13:c#中两个list不能直接copy,不然会出错,笔者就是因为直接拷贝出现了bug,可以通过for循环依次copy每个元素,不过笔者更推荐以下用法
//将carsNumber中的元素复制到CarsNumber中
CarsNumber.clear()
carsNumber.ForEach(i => CarsNumber.Add(i));
14:unity导出Pc端Apk时,按下Esc退出
void Update()
{
ExitByEsc();
}
public void ExitByEsc()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
//测试时不能执行,打包后可以执行
//Application.Quit();
//打包时不能执行
UnityEditor.EditorApplication.isPlaying = false;
}
}
15:设置rectTransform的位置
//VideoPlay是一个obj
VideoPlay.transform.GetComponent<RectTransform>().anchoredPosition3D = new Vector3(8f, -767f, 0f);