C#, Unity and Globals
One advantage that comes with age is wisdom, that is if we choose to learn from our mistakes. Relevant to this concept, this 2D Game Development course has been a challenge for me because preconceived ideas from experience have been getting in my way. This is not a problem, so long as I remain patient with the speed, or lack thereof, of my progress.
These past two days have been very productive because I’ve been able to refine a better way to create and use 1) global variables and subroutines, and 2) developed an improved way to manage and filter Debug.Log.
- Globals — in my earlier blog, I used a static class. But I began to see that I could not reference any monobehaviour class. And this was a big problem. I found the following solution worked by using static public variables and routines within a typical, Unity-centric monobehavior class as follows:
Step 1 — create a basic script as follows:
Be sure to read this script to understand my comments. You may not need the setMode routine, but it is an example routine.
Step 2 — in the opening scene, be sure to create an Empty object and attach this V.cs script to it. You will notice the “Awake” method uses DontDestroyOnLoad(this) reference so that this script remains accessible no matter what scene you are in.
2. Improving Debug.Log — use the following code to use an improved Debug.Log feature. As you read the code carefully, and the comments therein, you’ll see why this routine can be indispensable.
This week, I’m hopeful to finish the 2D Game Development Course including Phase Two! Thank you again to everyone who has made this project available.