[Solved]Adding Universally Available Methods

There are several utility methods I have for things like calculating where a turret should aim (using factors like projectile velocity and target position), or finding the component of a Vector3 that exists in a plane of reference. I plan to use these methods throughout my game project, so it feels kind of inefficient to have to copy-paste these methods throughout the code, or add a script with these methods to every single object that uses them.

I’d rather have a way to make these functions available like the Mathf functions - as something automatically usable by every script in the project. Does Unity provide any way to do this?

There are several ways you can reuse code. If you want something like Mathf, then you want a static class.

Example of static class in C#:

// Static class.
public static class ReusablePackage
{
   // Static function.
   public static DoSomething()
   {
   }
}

Excellent Document on Static Classes

Simplified version of that document:

How do you call a static function inside a static class?

ClassName.FunctionName();
ReusablePackage.DoSomething();

What is a static class?

  • You won’t be able to instantiate that class.
  • You will have a global access point to that class.
  • The class object will exist through the whole execution of the game.