当实例化的值在字符串中时,如何创建新的Vector4对象?

时间:2016-01-14 02:01:06

标签: c# vector unity3d text-parsing

我想创建一堆Vector4对象,并从配置文件中删除实例化的值,这些配置文件存储在字符串列表中。

字符串的值类似于“255,0,0255”或“0,025,255”等。

鉴于我正处于foreach循环中并且我即将创建这些Vector4对象,我将如何解析这些字符串,以便我可以提取出每个单独的整数并将其用于实例化,例如:

Vector4 v1 = new Vector4(255, 0, 0 255);
Vector4 v2 = new Vector4(0, 0, 255, 255);

请记住,我想让它成为一个自动过程,因此我有一个包含所有Vector值的配置文件。

2 个答案:

答案 0 :(得分:1)

拆分字符串,解析各个数字,然后将它们传递给构造函数。

string input = "255, 0, 0, 255";

var nums = input.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
                .Select(float.Parse)
                .ToList();

Vector4 v1 = new Vector4(nums[0], nums[1], nums[2], nums[3]);

答案 1 :(得分:0)

我喜欢Grant Winney提供的解决方案,但它无法处理Steven Chen要求的所有格式要求。分隔符也必须是空间本身。

另外,我喜欢将这些东西包装成扩展方法:)。 所以这里是稍微改进的版本,对错误的格式进行了一些测试,导致异常。

public static class StringVector4Extensions
{
    public static Vector4 ToVector4(this string str, params string[] delimiters)
    {
        if (str == null) throw new ArgumentNullException("string is null");
        if (string.IsNullOrEmpty(str)) throw new FormatException("string is empty");
        if (string.IsNullOrWhiteSpace(str)) throw new FormatException("string is just white space");

        if (delimiters == null) throw new ArgumentNullException("delimiters are null");
        if (delimiters.Length <= 0) throw new InvalidOperationException("missing delimiters");

        var rslt = str
        .Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
        .Select(float.Parse)
        .ToArray()
        ;

        if (rslt.Length != 4)
        throw new FormatException(  "The input string does not follow"     +
                                    "the required format for the string."  +
                                    "There has to be four floats inside"   +
                                    "the string delimited by one of the"   +
                                    "requested delimiters. input string: " +
                                    str                                   );
        return new Vector4(rslt[0], rslt[1], rslt[2], rslt[3]);
    }
}

用法很简单:

    var a =  "255, 0, 0 255".ToVector4(",", " ");
    var b =  "0, 0 255, 255".ToVector4(",", " ");