Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function 'class' in Unity/C#

Tags:

c#

unity3d

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?

like image 578
András Nagy Avatar asked Jan 01 '23 04:01

András Nagy


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.

like image 107
Anatoly Nikolaev Avatar answered Jan 02 '23 18:01

Anatoly Nikolaev


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.

like image 40
Hans Kesting Avatar answered Jan 02 '23 18:01

Hans Kesting