Clean-Up Day: New Tricks with 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).

  1. if (obj is ISource) {
  2.  ISource s = obj as ISource;
  3.     if (!s.isEndpoint) {
  4.        Connect (s);
  5.    }
  6. }

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.

  1. float i;
  2.  
  3. private void SomeMethod() {
  4.  // do some stuff here
  5.   i = 1f;
  6.     StartCoroutine(FadeOut());
  7. }
  8.  
  9. private IEnumerator FadeOut() {
  10.   while (i > 0f) {
  11.         yield return new WaitForFixedUpdate();
  12.      i -= 0.1f;
  13.  }
  14. }

 Delegates – The Easier Way

I wrote about delegates before, explaining how they could be used. I proposed that a new delegate had to be defined whenever you would want to use one.

Turns out, this is not even necessary – the System namespaces already has a delegate prepared for you, called Action.

  1. using System;
  2.  
  3. public class Example {
  4.     private Action DelegateMethod;
  5.  
  6.     private void Method() {
  7.         DelegateMethod();
  8.     }
  9. }

In case you use some parameters in your method, you could also use Func, which has parameters prepared.

Social Tags:
C#
C++
Obj
Product:

Neuen Kommentar schreiben