1

I am trying to extend Vector3 which is a Unity3D feature. It does not have a less than operator, so I am trying to create one. However, When I write the extension method for it, my IDE tells me "Identifier expected, 'this' is a keyword".

How can I write an extension method using operators? This is my attempt, which unexpectedly did not work:

using UnityEngine;
using System.Collections;

public static class Vector3Extensions
{
    public static bool operator <(this Vector3 vector3, Vector3 other)
    {
        if (vector3.x < other.x)
        {
            return true;
        }
        else if (vector3.x > other.x)
        {
            return false;
        }
        else if (vector3.y < other.y)
        {
            return true;
        }
        else if (vector3.y > other.y)
        {
            return false;
        }
        else if (vector3.z < other.z)
        {
            return true;
        }
        return false;
    }
}
Evorlor
  • 7,263
  • 17
  • 70
  • 141
  • here's a quick introduction to Extensions for any new Unity programmers googling to here ... http://stackoverflow.com/a/35629303/294884 Note that in Unity, extensions are the most basic thing - you use them constantly at all times. Almost all Unity code has extensions on almost every line. It's the "basic idea" of engineering in Unity, on the code side. – Fattie Jun 01 '16 at 12:47
  • how does this describe a vector less than another in the first place? assuming less or more would be reasonable terms for vectors. the only thing where less or more make sense is a vectors magnitude and you get that as a float. yes i know that has nothing to do with your actual question. – yes Jun 01 '16 at 14:03

2 Answers2

5

You can not use extension method to overload on operator. Perhaps you can add .LessThan.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
-2

It's not extension methods but operator overloads. See this MSDN documentation that states:

==, !=, <, >, <=, >= The comparison operators can be overloaded (but see note below). Note The comparison operators, if overloaded, must be overloaded in pairs; that is, if == is overloaded, != must also be overloaded. The reverse is also true, and similar for < and >, and for <= and >=.

Complete documentation here.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257