Hello Community,
I am just curious what for tricks do you use to keep your C# codes in unity efficient and small. So I would be pleased if you can share your tricks here and also discuss it with each other.
To give you an example I start with this easy boolean one:
First Boolean Code
Imagine you want to code your space rocket and set the isReady boolean to true, if you have enough fuel in your tank. So this code would do the job, but it is not efficient.
[Range(0f, 1f)] private float fuelPercentage; private bool isReady; private void Start() { if (fuelPercentage >= 0.9f) isReady = true; else isReady = false; }
You can compress it to this one:
[Range(0f, 1f)] private float fuelPercentage; private bool isReady; private void Start() { isReady = fuelPercentage >= 0.9f; }
Second Boolean Code
With that knowledge you can even go further. Image you don’t want to set only a boolean, but want also that another value will be set with the fuelPercentage. This code would do such a job, but is also not the efficient way.
private bool isReady; [Range(0f, 1f)] private float fuelPercentage; private int anotherValue; private void Start() { if (fuelPercentage >= 0.9f) { isReady = true; anotherValue = 50; } else { isReady = false; anotherValue = 10; } }
you can compress it to this:
private bool isReady; [Range(0f, 1f)] private float fuelPercentage; private int anotherValue; private void Start() { isReady = fuelPercentage >= 0.9f; anotherValue = isReady ? 50 : 10; }
So instead of creating big if brackets, you just can use what you would put into the if statement and put it directly into your variable. The “?” means, if the statement to the left of it is true, then pick the left value (50) from the “:”. Otherwise it will take the right value (10).
This was mine little efficient tip I can give you. Now I am really curious what nice programming codes you use, to make your scripts well organized.
P.S.: A nice screenshot from one of our projects.
