writing a utility (static) function properly

Hi, there’s something i couldn’t figure out, after reading about static functions and methods.

I have written a pathfinding utility, which i want to call from the most different contexts within my game (level generation, AI, and so on) so i’d like to call that class likewise Mathf.somefunction.
and it has come to my understanding that i should use a static function, which requires all it’s variables to be static.

And here’s the problem.

the FindShortestPath() function, returning a List of Vector3, has some internal Lists, (declared outside the methods, so they can be accessed by all the functions, i wrote for pathfinding) and making them static, is just a nonsense.

So, since I may be wrong on any of my assumptions, my real question is, is there a way for calling a “utility” function from anywhere, with no need to call it from within an object, and let that function have it’s own internal instances ?

var newPath_ : List.<Vector3> = new PathfindClass.FindShortestPath(startingpoint, endpoint);

Thank you for your time.

You might look at the singleton pattern - an example for unity is here. However this could be viewed as the same thing as making all your members static - since by definition of a singleton there can only be one instance.

It sounds to me that you have a design problem. I would separate the actual logic of finding paths out into a non static class. Say “PathPlanner” or something. If the PathPlanner needs access to common info, for example the world navgrid, that should be separated out into a separate class say “NavGrid” and passed as an argument. So in this case to find a path you might use:

PathPlanner newPlanner = new PathPlanner();
newPlanner.FindShortestPath(startPoint, endPoint, navGrid);

Having stuff like the NavGrid separated is good idea anyway - as is seperating the path planner because otherwise two objects can’t pathfind at the same time.

Once the design is properly separated like this it is very simple to write a utility class like so:

public static class PathFinding
    private static NavGrid mNavGrid; // The global nav grid
    public static List<Vector3> FindShortestPath(startPoint, endPoint)
        PathPlanner newPlanner = new PathPlanner();
        return newPlanner.FindShortestPath(startPoint, endPoint, mNavGrid);