- Home /
using non static variable in static function
Here's my problem:
I want to use a normal variable within a static function.
Of course this doesn't work unless the variable itself is static as well. My workaround so far has been to create a copy of that variable as a static variable, then assigning the normal variable to the static version in in Start or Update, and using the static version in my static function.
public float myNormalVar;
public static float MyStaticVar;
void Start() {
MyStaticVar = myNormalVar;
}
The other workaround I tried was turning my class into a singleton, and using a static property to return an instance of my normal variable:
public float myNormalVar;
public static float MyStaticVar { get{ return instance.myNormalVar; } }
But I don't want to turn this class into a singleton, there's never gonna be 2 instances of that class so using static variables works perfect for it.
I was wondering, am I doing this the right way or is there another way to use non-static variables within static functions?
Thanks for your help!
Stephane
Answer by Waz · Jul 25, 2011 at 12:04 AM
A singleton is the way to go. You list a lot of contradictory "I want" without saying why, so it's hard to give more advice. If your reason for wanting to use a normal variable is so that it shows in the inspector then a singleton is precisely the correct way to achieve that. It's up to you whether you want the variables that do not need to appear in the inspector to be static or member variables accessed through the singleton.
As for "there's never gonna be 2 instances of that class", well yes, that's always the case for singletons.
Thanks for your answer Warwick, and sorry for my vague question!
I guess I still get a little confused on when to use a Singleton and when to use a class full of static variables.
$$anonymous$$y class checks for WheelCollider collisions with the ground, and store the information in multiple static variables which I access from many other classes. For most of those static variables, i do not need to see them in the inspector, but for some, I do need to see them in the inspector but still be able to access them from all other scripts "easily" like a static variable.
So even though my question was vague and missing some information, I think you nailed it in your answer. A Singleton is probably the way to go for my particular issue.
Thanks again!
Your answer
Follow this Question
Related Questions
Using static properties that return _instance.variable... 0 Answers
Static function and variables error 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
variable = true from another script 2 Answers
how to make function parameters don't need to declare (custom parameters)?? 1 Answer