-1

I'm trying to understand namespaces and use them to keep my project tidy. As far as I understand, all functions need to be contained within a class in the namespace:

using ProjectDTools;

namespace ProjectDTools
{

    public class MathTool
    {
        public Vector3 RoundToDiscrete(Vector3 pVector){
                Vector3 tVector = pVector;
                float tempX = tVector.x;
                tempX = (float)Math.Round(tempX, MidpointRounding.AwayFromZero);
                float tempZ = tVector.z;
                tempZ = (float)Math.Round(tempZ, MidpointRounding.AwayFromZero);
                tVector.x = tempX;
                tVector.z = tempZ;
                //Debug.Log("Rounded vector to" + tVector.ToString());
                return(tVector);
    
        } 
    
    }

}

I then apparently need to instantiate this class in order to use the method:


void Start()
{
mathTool = new MathTool();
}

tVector = mathTool.RoundToDiscrete(someVector);

I would rather use the method by referencing the class type:

tVector = MathTool.RoundToDiscrete(someVector);

If I try it like that I get the following error:

An object reference is required for the nonstatic field, method, or property 'MathTool.RoundToDiscrete(Vector3)'

Any Ideas?

D-Shih
  • 44,943
  • 6
  • 31
  • 51

2 Answers2

4

The method must be static if you want to call it from the class name.

public static Vector3 RoundToDiscrete(Vector3 pVector)
Tsuu
  • 96
  • 1
  • 6
1

You can call the method without object instantiation if you make the method static.

See this Unity QA:

public class MyClass {
    public static float Multiply (float a, float b) {
        return a*b;
    }
}

product = MyClass.Multiply(3, 2);
code11
  • 1,986
  • 5
  • 29
  • 37