- Home /
Adding static functions
Alright I guess this is more of a general programming question, but here goes; I want to make my function / script always active without it being added to the scene. I have a few different functions I use in many different scripts. Adding the script to the scene and pointing to it from the other scripts is a troublesome process. Is it a good practice to make such function static? Is there another way out?
This is one of the functions I use a lot
//Gets the vector3 from a string
public Vector3 getVector3(string rString){
string[] temp = rString.Substring(1,rString.Length-2).Split(',');
float x = float.Parse(temp[0]);
float y = float.Parse(temp[1]);
float z = float.Parse(temp[2]);
Vector3 rValue = new Vector3(x,y,z);
return rValue;
}
This is the script I've made with the function(s)
using UnityEngine;
using System.Collections;
public static class MyFunctions {
public static Vector3 getVector3(string rString){
string[] temp = rString.Substring(1,rString.Length-2).Split(',');
float x = float.Parse(temp[0]);
float y = float.Parse(temp[1]);
float z = float.Parse(temp[2]);
Vector3 rValue = new Vector3(x,y,z);
return rValue;
}
}
Answer by MaT227 · Jul 27, 2014 at 01:12 PM
You are right this is more like a general programming question. Of course you can create static class with static value and static functions or a classic class but with static method and classic method.
It's up to you, it could be useful if you work in a team and create static functions accessible for other developers. It's also useful because using gameobjects in the scene consumes resources and affect performances and if you can use a static class with static functions why not doing it :) it will save ressources.
A great example is the Mathf class in Unity, there's no advantage of create a classic class, just do a static class and here we go.
Here is an interesting question asked on StackOverflow : Performance of static methods vs instance methods
Answer by smallbit · Jul 27, 2014 at 01:15 PM
Another option would be the singleton pattern.
http://unitypatterns.com/singletons/
Also if you don't want to to place your script in the scene at all, you can define a class that is not inheriting from MonoDevelop.
Of course, it depends of the usage. It's more related to pattern program$$anonymous$$g. A Singleton Pattern is adapted to manager classes for example.
Your answer
Follow this Question
Related Questions
Static function and variables error 2 Answers
Accessing non static members in a static function argument?? 1 Answer
Custom Global Functions 1 Answer
C# script for calculating the distance between the player and objects 1 Answer
Simple static function to display text onscreen (Accessible from anywhere) 1 Answer