- Home /
Make my script accessable just by its namespace?
Preferrably I don't want to have to "find" the script or make an instance of it with a singleton work-around to use its functions and stuff, is there any way to make the script open and accessable from another script as if the function was right here, except by namespace?
like if I have mathutils.cs: class mathutils { void multiplication(int x, int y) {whatevz;} }
And then in another script called gamelogic.cs I'd like to be able to just write mathutils.multiplication(1, 2); anywhere in the gamelogic.cs.
Is this possible? mathutils needs to be singleton, but I'd like to be able to also create instances of subclasses inside mathutils if possible.
Thanks a bunch in advance!
Answer by Hoeloe · Apr 08, 2014 at 11:08 AM
Also, if you want to use methods or variables without specific object references; that is, using something like:
MyClass.Method();
Instead of:
MyClass c = new MyClass();
c.Method();
Have a look at static members.
On an unrelated note, it's good practice to use capital casing for your class names (e.g. MathUtils
instead of mathutils
) to separate them from variables, which usually use lower camel-casing (e.g. myVar
instead of myvar
or MyVar
). It keeps your code neat and prevents confusion later.
$$anonymous$$aking it static has the effect I want, but the problem is "cannot declare instance members in a static class"?
Is there any way to get the same effect of making it static and being able to just write $$anonymous$$yClass.$$anonymous$$ethod(); while still being able to create instances of subclasses and such?
Also; if I use "$$anonymous$$yClass c = new $$anonymous$$yClass();" how do I make $$anonymous$$yClass singleton for this purpose?
You need to make the method static, not the class. Please read the page about how static works again and make sure you fully understand it.
Answer by NachoUJI · Apr 08, 2014 at 11:59 AM
You can create the object, not being part of the scene:
class Mathutils {
public void multiplication(int x, int y)
{
retutn x*y;
}
}
Then in the other script you can do:
Mathutils objectMath = new Mathutils();
objectMath.multiplication(myX, myY);
You don't need to write the ":MonoBehaviour" in the declaration of the class.
Hope it helps.