- Home /
Reusable function in multiple scenes
I have a simple function in scene 1 that checks to see if i can spawn that gameobject (check if player is there) I need this function to be usable on other gameobjects in other scenes. How would i go about that? It is currently a monobehavior on an empty object that gameobjects in scene 1 call.
The initial plan was to put that empty object with script into all scenes but wasn't sure if there was a cleaner way.
Answer by Isaac_Medina225 · May 14, 2021 at 11:40 PM
@HBishop You may use static modifier:
public class TestFunctions : MonoBehaviour
{
// This is how I make a method that I can use on other class
public static float ReusableFunction(float num)
{
return num * num;
}
// This is how I make a method that I can use on other class
public static void ReusableMethod() {
Debug.Log("Hello World");
}
}
Other class call methods and functions:
public class OtherClass : MonoBehaviour
{
private float someVariable;
void Start()
{
someVariable = TestFunctions.ReusableFunction(0.5f);
Debug.Log(someVariable);
TestFunctions.ReusableMethod();
}
}
Would the test function class be on a gameobject in the scene. Or is it a static class that isn't attached? Which would be better? Thank you for your really fast and concise response!
You don't need to put the TestFunction class on a game object you can call on other class. it happens because of the static you may try adding static on the function that you want to call on other class :)
I thought all monobehaviour classes had to be attached to a gameobject. How does the static keyword in front of the function make this not needed to be attached for the Test Class?
Just had a go now I'm back at my computer and it currently keeps popping up with an error saying NullReference: Not set to an instance of an object
Thanks :)
You can still call it even if you don't put it on the game object since you put static keyword on your function.
You just need to type your class name that has the static function. In the code above that I provide, I can call the function on the other class without putting the TestFunctions class on the gameobject. I call it's function using TestFunctions.anyPublicFunctionWithStaticKeyword
Answer by logicandchaos · May 16, 2021 at 01:54 AM
If you just have it on an empty gameObject why make it a monobehaviour at all? You could make your own class and make it static and use it anywhere without having to worry about gameObjects.
Thats great, sounds less messy than having gameobjects everywhere
Public TestFunction{
public static void ResuableMethod() { Debug.Log("test") } }
Like that? Thank you! :)
Yes, you can do that too, in my case, its working even if I didn't remove monobehavior
Your answer
Follow this Question
Related Questions
Randomise pixel offset to create TV static effect 1 Answer
Static Variables Issue 0 Answers
Use Of Static Variables 1 Answer
Am I "misusing" the concept of statics with this implementation? 1 Answer
Static reference cost 1 Answer