I was just wondering about an optimization idea that I have that I don’t know if its good or bad.
I have multiple objects that references to the player and to the players ai script.
So instead of storing those to things locally on a variable on every object that interacts with
them I use 2 global variables instead.
Is that a good idea? I have had an issue when I testing that, like I get lots and lots of
errors in my log telling me that the global variable has not been set when i work in the scene.
First after I have played the level once the errors stop occurring.
Is that something that can bite me in the ass later after a build or something that is just
occurring in the editor? Is there a way to set these variables on scene load or application
start to remove these errors?
Depends on the language you use, on c# you would mostly initialize every variable if possible (like string abc = “” to prevent errors. Also if you use statics, you need to attach it to an object if you want to use some Start() functions to fill some variables, also remind that you need some test values in your files while working in the editor as you need to load the statics at least once to get the values (only if you need some functions, variable-only-statics will work just fine). It’s some fiddeling here ad there, but it could be worth it, as you only need to change 1 variable and all scenes/scripts/whatever will be updated, also you don’t need to re-create each variable locally, you can simply get it by e.g. statics.variable (if you called the file statics), oh and also remind that static variables can only store 1 global value (they are not object-related like creating prefabs that all have their own private variables if you created some).
Thanks for your answers.
I haven’t been programming for so long and never really used global variables before.
I have looked around to get some idea for what global var can be useful for and the
performance impact they have. I haven’t really found any good answers on this.
I am using C# and I tried to initialize the global var like this:
public static transform = transform; but that didn’t work. Probably a no brainer for
an experienced programmer but as I said never really used them before.
So I set it in awake to get it loaded before everything else.
I’d love to read up on them to get some more knowledge on the matter
edit: Oh just found out that if an object doesn’t use global var in the start function
(like GetComponent) I never get the error messages on scene open. Lovely