U3D (C#)常用的數據類型轉換

C#的值類型(在C#中所有的值類型都繼承自:System.ValueType

整型:Int; 長整型:long; 浮點型:float; 字符型:char; 布爾型:bool; 枚舉:enum; 結構:struct;

Double / Float / Int

    double A = (double)floatOrInt;
    float B = (float)IntOrDouble;
    int C = (int)floatOrDouble;

* float 使用Mathf.,double使用Math.

Int / Float / String

float B = 0;
int C = 0;
string s = B.ToString();
string s = C.ToString();
float.TryParse(s, out B);
int.TryParse(s, out C);

C# Tostring 格式化輸出字符串全解

Byte[] / Char[] / String

Byte[] bb = Encoding.UTF8.GetBytes(s);
string s = System.Text.Encoding.UTF8.GetString(bb);
Char[] cc = s.ToCharArray();
string s = new string(cc);

Int / UInt / Long / ULong


Float取整到N的倍數

    before = 321f;
    float j = before/10;
    after = Mathf.Round(j) * 10;
    //j = 32.1
    //after = 320
    
    before = 50;
    float k = before/8;
    after = Mathf.Round(k)*8;
    //k = 6.25
    //after = 48

	int i = 36 / 10; // 3.6
	int j = 36 % 10; // 6

* 小數位爲5時向偶數取整

Vector3 / Quaternion

vec3 = gameobject.transform.eulerAngles;		//vec3 -> quaternion
gameobject.transform.rotation = Quaternion.Euler(vec3);	//quaternion -> vec3
gameobject.transform.localEulerAngles = vec3;			//quaternion -> vec3

Texture2D / OpenCVSharp.Mat

MatA = Unity.TextureToMat(this.TextureA);
draughtMapMat.ConvertTo(draughtMapMat, MatType.CV_8UC1);

Texture2D texture = Unity.MatToTexture(draughtMapMat);

Texture2D / sprite

this.GetComponent<SpriteRenderer>().sprite = 
	Sprite.Create(texture, new UnityEngine.Rect(0, 0, texture.width, texture.height), Vector2.zero);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章