I’ve been using Unity and C# for a few months now and have always wondered about the various ways to access scripts on another object. For instance, I usually cache the references (using GetComponent) in Awake/Start and this does work well enough but can sometimes bloat the functions if there are many scripts that I need access to.
Another method that Ive recently starting using is to create a public static Scriptname reference;
in the script I want to access, which then references the script using Scriptname.reference = this;
and then used in other scripts by calling Scriptname.reference.variable/function;
to access what I want. I’ve found this to be generally easier to read that the other method
I was wondering if anyone can give me an overview of when to use each method (or any others that I don’t know about), both from a performance as well as a neatness/elegance point of view.
Thanks in advance.
I’ll tell you what I know –
Generally, static instance variables are used when you need to access ONE specific GameObject such as a camera or something that there’s only ever one of. It makes it easier than getcomponent because you could do something like “PlayerCam.Instance.Hero = null.”
Caching GetComponents is a very good way for scripts to talk to each other. The performance expense comes in when you call it every frame (doesn’t sound like that’s your issue)
-As far as I’m aware- Caching GetComponents is approximately 100x faster than SendMessage (can’t quote the post, found it a few months ago).
Basically, for performance you want to Cache GetComponents and use SendMessage as sparingly as possible. As with damage functions, using either an instanced GetComponent or SendMessage, I -believe- SendMessage would be superior simply because you need to get the individual unit per damage interval.
What I personally did for (at least temporarily) my scripts was parent them. I have approximately 30 “state” scripts including health movement speed object state orientation etc, and I broke them down into “StatManagers,” “ActionManagers,” “Animations,” and “Skills.” The parent script has each object GetComponent-ed and I can reference each instance of each variable with only the basic 30 GameObjects “parented” to each other. If any script needs any value, I can easily do parentObject.GetComponent(Parent).Stats.Health.Current, for any “state” script.
Just my 2c, I know that at least a majority of it is true including the caching of GetComponents and SendMessage’s performance. Optimization is a thing that takes the back burner until you know that something has to change because people tend to over-think organization and end up scratching their heads at their own code.