Hey guys. Just trying to broaden my understanding on some things.
Been wanting to use the inspector less and less when gaining access between scripts.
Ran into some issues that still stump me.
Why can’t I call expansion_check inside the Profile class?
Says I cant do it cause its not a static member. So I’m guessing this has something to do with script instances.
public class Profile: MonoBehaviour {
AutoLoginManager.expansion_check();
}
public class AutoLoginManager : MonoBehaviour {
public void expansion_check(){
}
}
I’m starting to get to a point where I really need a function page of functions I use often.
So I need to figure out how to access a class with a list of functions that I can use over and over again with out using the inspector to assign the component.
If someone could help me understand this would go a long ways with me in development.
The expansion_check method is an instance method. This means that you need an actual AutoLoginManager instance (an object) to use it.
So if you have a GameObject with an AutoLoginManager on it, you find a reference to it through GetComponent, and call the method on the instance:
//assume we have a gameObject named "someObject" with an AutoLoginManager component added to it
AutoLoginManager manager = someObject.GetComponent<AutoLoginManager>();
manager.expansion_check();
If it doesn’t really make sense that the AutoLoginManager is attached to a gameobject - it doesn’t sound like it does - it shouldn’t be a MonoBehaviour. If it only contains methods that does checks against a server or whatever and doesn’t have any states that changes it’s behaviour, it should be a static class instead.
Ya I don’t need instances of AutoLoginManager.
I have several scripts just in this scene that doesn’t need instances to it.
If I create a static class. What things do I lose with it not being inside MonoBehaviour?
Do I lose any inspector stuff? Like public variables showing up in the inspector.
Static classes are not monobehaviours so yes you will lose all the inspector access to public variables as they cannot be added to a gameobject. The singleton approach mentioned in the previous method is what I’ve used for years and works very well. However be careful not to abuse it by making everything a singleton as you can get lazy in programming and break the structure of your system by calling methods from everywhere. I tend to use singletons on manager classes that should standalone then let those handle sub objects.
That doesn’t mean statics should be avoided as they have uses. If you are always going to use the class then making it static makes sense but if its a class that is only used in 1/2 of your levels then make it a singleton as the class isn’t instantiated and so saves memory when its not needed!