将字符串转换为Vector3

时间:2017-06-05 05:15:36

标签: c# mysql

我在MySQL数据库中有这个字符串:

" -1035.43,-2728.861,13.75664"

如何将其转换为Vector3以在此函数中使用它:

Vector3 newpos = new Vector3(getChar[15]);
API.setEntityPosition(player, newpos);

getChar是数据库列表,15是值。

2 个答案:

答案 0 :(得分:2)

拆分string并提取坐标:

float[] newPosCoordinates = getChar[15].Split(new string[] { ", " }, StringSplitOptions.None).Select(x => float.Parse(x)).ToArray();
Vector3 newpos = new Vector3(newPosCoordinates[0], newPosCoordinates[1], newPosCoordinates[2]);

答案 1 :(得分:1)

Vector3 ConvertFromString(string input)
{
    if (input != null)
    {
        var vals = input.Split(',').Select(s => s.Trim()).ToArray()
        if (vals.Length == 3)
        {
            Single v1, v2, v3;
            if (Single.TryParse(vals[0], out v1) &&
                Single.TryParse(vals[1], out v2) &&
                Single.TryParse(vals[2], out v3))
                return new Vector3(v1, v2, v3);
            else
                throw new ArgumentException();
        }
        else
            throw new ArgumentException();
    }
    else
        throw new ArgumentException();
}

以下是您提供的字符串的结果: enter image description here