I’m trying to access a function from another script but I get an error telling me it needs to be static, when I do this I get a new error saying I need to make each variable being used also static - is there a way to avoid this?
Make the variable static too (which is what I do) and alternatively if it has to be private (shared script), then use SendMessage instead to call the function in a safe manner without making the function static.
as a reminder inside a static fct you can’t have instance variable, so either you declare local var inside the fct directly when you call it , or as hippoder say declare the var you want to use in this fct static too, and of course you can use whatever argument you pass in this function(those will be eventually instance variable…).
If you want to access a function from another script, it doesn’t has to be static.
Here is an example:
class WTFisThis : MonoBehaviour{
var IamNotAnAsshole : boolean = true;
var DaySpentOnTheGame : int = 200;
function WTFisThis(){}
function LetMeSleep(){
Debug.Log("I know the deadline is close but I really want to sleep!!!");
}
}
After you attach this script to a GameObject named… let say “Test”
Then you just have to drag the GameObject “Test” to the inspector of another GameObject which has the script bellow:
class IamAnotherScript{
var TargetScript : WTFisThis;
function LetMeCallAnotherScript(){
TargetScript.LetMeSleep();
}
}
you aren’t accessing a function there but an object and a method on the same. Thats not the same as a static function which is completely independent from objects.
this and if you want access this function from more than one object or doing so in a complex project , that will become quickly a hell of drag and drop XD …tho that 's ok on small scope.
Yea I know…
But Apple741’s question is “How to avoid setting everything to be static but still be able to access a function from another script.”
So I think this is the only solution.
Of course an alternative way is you can make the whole GameObject to be static so that you can get the component directly through script or use SendMessage. But again, if he doesn’t want to use static, he has to drag n drop like hell lol~
The correct solution to that case is called Singleton Pattern.
It bases on this naturally but is no sluggish “good luck” solution that uses “some object” but one granted to be present, always the same, global object, the singleton of this class