Is there any way to create operators for existing unity classes and structs ?


I'm trying to create some operators like + and - for Rect and Vector3. I can do this with my own classes but for some reason can't do it with unity classes. Is there any way to do that?

Thanks in advance.

You can use extension methods to create your own methods that function like they are part of the struct, but you cannot use this to do your own operator overloading. Something like this might work for you though:

public static class MyExtensionMethods {
    public static Rect Add(this Rect rect1, Rect rect2) {
        Rect result = new Rect(/*some new operation combining the 2 rects*/);
        return result;

then you could call this just like it was part of the Rect struct:

Rect rect1;
Rect rect2;

Rect resultantRect = rect1.Add(rect2);

  • You can't define new operators for structs, since you can't inherit from structs.
  • You can't create new operators in a new class, since one of the parameters of a binary operator must be the containing type.
  • You can't expect to allow plus operator to work if you have the interface to something that doesn't provide it.
  • You can use extension methods, or classes with helper methods as Peter G mentions in his answer.