坐标轴的适当类型?

时间:2013-12-31 08:32:51

标签: c# constructor unity3d

我在声明变量axis的构造函数类型时遇到了问题。我试过漂浮,但显然它没有用。

private void SortDistAxis(List<Transform> targetsList, var axis)
{
    targetsList.Sort(
    delegate (Transform t1, Transform t2) 
    {
            return selectedTarget.Find("localChild").transform.InverseTransformPoint(t2.position).axis.CompareTo 
                (selectedTarget.Find("localChild").transform.InverseTransformPoint(t1.position).axis);
    });
}

我可以采用这种方法,但感觉很脏。还有其他选择吗?

private void SortDistAxis(List<Transform> targetsList, string axis)
{
    if (axis == "x")
    {
        targetsList.Sort(
        delegate (Transform t1, Transform t2) 
        {
                return selectedTarget.Find("localChild").transform.InverseTransformPoint(t2.position).x.CompareTo 
                    (selectedTarget.Find("localChild").transform.InverseTransformPoint(t1.position).x);
        });
    }
    if (axis == "y")
    {
        targetsList.Sort(
        delegate (Transform t1, Transform t2) 
        {
                return selectedTarget.Find("localChild").transform.InverseTransformPoint(t2.position).y.CompareTo 
                    (selectedTarget.Find("localChild").transform.InverseTransformPoint(t1.position).y);
        });
    }
}

3 个答案:

答案 0 :(得分:3)

也许你可以考虑使用委托来获得你想要的轴?

private void SortDistAxis(List<Transform> targetsList, Func<PointF, float> axisFunc)
{
    targetsList.Sort(
    delegate (Transform t1, Transform t2) 
    {
         return axisFunc(selectedTarget.Find("localChild").transform.InverseTransformPoint(t2.position)).CompareTo 
               (axisFunc(selectedTarget.Find("localChild").transform.InverseTransformPoint(t1.position)));
    });
}

用法是:

SortDistAxis(targetsList, p => p.x);
SortDistAxis(targetsList, p => p.y);

我假设InverseTransformPoint返回的类型是PointF

答案 1 :(得分:2)

您不能直接在C#中执行此操作(运行时代码修改),但这是顺便进行的; 您可以代替Vector3[index]代替Vector3.x, Vector3.y, Vector3.z

enum Axis {
  X = 0,
  Y = 1,
  Z = 2
}

private void SortDistAxis(List<Transform> targetsList, Axis axis) {
  targetsList.Sort(
  delegate (Transform t1, Transform t2) {
    return selectedTarget.Find("localChild").transform.InverseTransformPoint(t2.position)[axis].CompareTo 
                              (selectedTarget.Find("localChild").transform.InverseTransformPoint(t1.position)[axis]);
  });
}

答案 2 :(得分:1)

您建议的内容无法在C#中完成。您应该创建一个枚举并将其作为轴参数传递。您更新的代码看起来像这样

enum Axis
{
    X,
    Y
}

private void SortDistAxis(List<Transform> targetsList, Axis axis)
{
    if(axis == Axis.X)
    {
        // ...
    }
    else
    {
        // ...
    }
}