How to Overload an Operator in JavaScript/UnityScript?

164 views Asked by At

I asked this question on Unity Answers, but yet again there was no response. Now I'm hoping someone on SO will happen to know the answer since it is a programming question.

There are quite a few of these questions, but I couldn't find any more recent than about 2009 and a lot has changed since then. So...

In Unity 5, is it possible to overload an operator (specifically the + operator) when using JavaScript/UnityScript?

-- Additional Information --

I have a class like so:

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;
    }
}

I wish to be able to do the following...

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

print(position1+position2);

...and have the output be 88,42,146.

2

There are 2 answers

1
Sekretoz On

i guess it wont be possible to add two class directly.try this code to add value of two class:

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 to get sum of two classes

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);
    }
}

main class

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);
    }
}
3
Ilona Hari On

You could try the following:

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);
}

}

To test:

  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);

Hope this helps