I’m finishing up my first project in Unity (C#) and I’m wondering if the standard way that I declare variables isn’t a good best practice.
Basically, if I know that I need a variable in a script, I just declare it up front (outside of any of my methods) so that I have my necessary variables or references. I rarely declare variables within my methods or functions unless I have to for some reason. As I understand it, doing it this way is allocating the memory for these variables to the “stack”, so it’s always in memory even if I don’t currently need it.
My reason for doing this was largely because as I was learning to code, I assumed that “declaring” a variable had some overhead, and I wanted to get it out of the way up front so it wasn’t impacting performance later as my scripts run. I realize now (as I learn more) that this isn’t really the case, but I’m trying to understand what the best practices are for this. Is there a general rule of thumb for when I should allocate a variable up front to the stack, vs. when I should only allocate them within my methods and functions (on the heap)? From my research on this it seems like reference type variables should go on the stack, and value type variables that don’t need to be persistent over time in some way should go on the heap.
Assuming I don’t have any memory consumption issues (my project uses very little memory), am I doing this wrong by just putting everything on the stack?