C#
Since I'm currently cleaning up my code to hand it in with my project, I figured I could write some of the stuff down I learned during my work on our game.
All of it applies, of course, to C#, and was used in Unity 3D.
Checking for a type
Using the is keyword, you can easily check whether a certain object is of a desired type. Also, you should be aware of the as keyword, that allows you to cast an object as something else (given that this is possible).
if (obj is ISource) { ISource s = obj as ISource; if (!s.isEndpoint) { Connect (s); } }
Modelling Behaviour Over Multiple Frames Without Update()
Sometimes, you need to model some behaviour over several frames (like fading stuff in or out), but doing it in Update() or FixedUpdate() would require unwieldy if constructions.
So ... coroutines to the rescue! Using WaitForFixedUpdate(), you can model a behaviour over several frames without using FixedUpdate(), and quits as soon as it is done.
float i; private void SomeMethod() { // do some stuff here i = 1f; StartCoroutine(FadeOut()); } private IEnumerator FadeOut() { while (i > 0f) { yield return new WaitForFixedUpdate(); i -= 0.1f; } }
Delegates – The Easier Way
I wrote about delegates before, explaining how they could be used.
(This is only here for personal reference, since this is rather basic programming …)
/// <summary> /// Formats the input string (in seconds) as a human readable /// string in the form of MM:SS. /// </summary> /// <returns> /// A <see cref="System.String"/> of the current playing time. /// </returns> private string formatedTimeString (string input) { int seconds; int minutes; minutes = Mathf.FloorToInt(input / 60); seconds = Mathf.FloorToInt(input - minutes * 60); string r = (minutes < 10) ? "0" + minutes.ToString() : minutes.ToString(); r += ":"; r += (seconds < 10) ? "0" + seconds.ToString() : seconds.ToString(); return r; }
When preparing my game for Fantoche, I ran into problems several times, since upon building my game, the screen either remained black or parts of my game did not work, with the log showing a NullReferenceException.
In both times, it was related to me tagging objects in the Unity 3D editor. This is caused by the somewhat peculiar implementation of tagging in Unity which only allows one tag to be added to an object.
Pitfall No. 1: EditorOnly
Tagging objects in the editor as EditorOnly will make the game work in the editor – but not in the build, as those objects won't be included when building your game.
Pitfall No. 2: Trying to Access One of Several Objects with the Same Tag
When accessing GameObjects using the FindObjectsWithTag() function, make sure that only one object has this tag added.
The function returns the first object with this tag it encounters.