Function 'class' in Unity/C#

Viewed 294

I'm new in Unity. My question isa, is it possible to create function files, without constructor and other stuff? In flash actionscript 3 it's look like this:

package util
{
    public function getRandomNumber(minQ:Number = 0, maxQ:Number = Number.MAX_VALUE):Number 
    {
        return minQ + Math.random() * (maxQ - minQ);
    }   
}

Is it possible to do somthing similar like this?

2 Answers

No, it is impossible in C#. I suggest you learn about Extension Methods and Partial classes.

You can use static classes and singletons as well, but try to avoid the temptation to access it from every part of your project - it will be difficult to modify and refactor it in the future.

You cannot create a global function, but you can create a static method in a static class:

namespace MyNamespace
{
   public static class Util
   {
      public static double GetRandomNumber(..) { ... }
   }
}

and use it like

var myNumber = Util.GetRandomNumber(...);

The important part here is that the method is static, which means that you don't need an instance of the class to call it. The static class means that it is impossible to create an instance of that class.

Related