【问题标题】:How to Overload an Operator in JavaScript/UnityScript?如何在 JavaScript/UnityScript 中重载运算符?
【发布时间】:2015-06-09 12:20:59
【问题描述】:

我在 Unity Answers 上问过这个问题,但还是没有任何回应。现在我希望 SO 上的某个人碰巧知道答案,因为它一个编程问题。

这样的问题有很多,但我找不到比 2009 年更近的问题,而且从那以后发生了很多变化。 所以...

在 Unity 5 中,使用 JavaScript/UnityScript 时是否可以重载运算符(特别是 + 运算符)?

-- 附加信息--

我有这样的课:

class Vector3Int
{
    var x:int;
    var y:int;
    var z:int;
    function Vector3Int(nX:int,nY:int,nZ:int)
    {
        x=nX;
        y=nY;
        z=nZ;
    }
}

我希望能够做到以下...

var position1:Vector3Int=new Vector3Int(5,39,-2);
var position2:Vector3Int=new Vector3Int(83,3,148);

print(position1+position2);

...输出为88,42,146

【问题讨论】:

  • 你能举个例子说明你想做什么吗?
  • 我创建了一个 Vector3Int 类,如下所示: class Vector3Int { var x:int;变量 y:int;变量z:int;函数 Vector3Int() { x=0; y=0; z=0; }
  • 糟糕,我会努力让它可读...
  • @Sekretoz 我有一个 Vector3Int 类(里面只有 x、y 和 z 变量),我希望能够轻松地将它们中的两个加在一起,或者将 Vector3Int 添加到内置 Vector3。之类的东西。在 C++ 中非常简单。
  • 你想添加x和y的例子?

标签: javascript operator-overloading unityscript


【解决方案1】:

我想直接添加两个类是不可能的。试试这个代码来添加两个类的值:

using UnityEngine;
using System.Collections;

public class NewBehaviourScript{
     public int x;
     public int y;
     public int z;


    public NewBehaviourScript(int nx,int ny,int nz){
        x = nx;
        y = ny;
        z = nz;
    }

}

class 得到两个类的总和

using UnityEngine;
using System.Collections;

public class sum {

 public NewBehaviourScript sumOfTwoClass(NewBehaviourScript a, NewBehaviourScript b)
    {

        return new NewBehaviourScript (a.x + b.x, a.y + b.y, a.z + b.z);
    }
}

主类

using UnityEngine;
using System.Collections;

public class sample : MonoBehaviour {

    NewBehaviourScript zzz;
    NewBehaviourScript xxx;
    public NewBehaviourScript sum;
    // Use this for initialization
    void Start () {
        zzz = new NewBehaviourScript (1, 2, 3);
        xxx = new NewBehaviourScript (3, 2, 1);
        sum = new sum ().sumOfTwoClass (zzz, xxx);
    }
}

【讨论】:

  • "sumOfTwoClass" 这是我试图避免的。我已经使用了那个 hacky 解决方案,但我想要一个更整洁更好的方法。感谢您的尝试:)
【解决方案2】:

您可以尝试以下方法:

public class Vector3Int {
public  int x;
public int y;
public int z;

public Vector3Int(int nX, int nY, int nZ)
{
    x=nX;
    y=nY;
    z=nZ;
}

public static Vector3Int operator +(Vector3Int c1, Vector3Int c2)
{
    return new Vector3Int(c1.x + c2.x, c1.y + c2.y, c1.z+c2.z);
}

}

测试:

  Vector3Int a = new Vector3Int(1, 2, 3);
    Vector3Int b = new Vector3Int(4, 5, 6);
    a = a + b;
    Debug.Log(a.x +" "+a.y+" "+a.z);

希望对你有帮助

【讨论】:

  • 这也是 JavaScript 吗?
  • 这不是 Javascript,它是 C#..据我所知,你可以用 C# 编写类,而不是在 Javascript 中使用它们:)
  • 什么?如何?我不会写C#,更不会在JS中使用它的类! :S
猜你喜欢
  • 2010-12-15
  • 1970-01-01
  • 2010-12-10
  • 2021-08-01
相关资源
最近更新 更多