'Namespace method without class instatiation [duplicate]
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?
Solution 1:[1]
The method must be static if you want to call it from the class name.
public static Vector3 RoundToDiscrete(Vector3 pVector)
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | khaitruong922 |
| Solution 2 | code11 |
