C++ classes
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.
A simple walker script for Unity 3D in C# that tries to avoid obstacles. It has been used in the ProXedural project at art school, and it made the cows walk towards one of the players. To be honest, it does not really deserve the I in AI. But then again, no one expects cows to be very clever.
Maybe someone can use it as a base to produce something better (oh well, who am I kidding, this has already been done).
using UnityEngine; using System.Collections; /// <summary> /// A simple AI walking script. Follows a target. /// </summary> public class AIWalker : MonoBehaviour { internal Vector3 target; private CharacterController controller; private int counter = 0; private Vector3 avoidNormal; private Vector3 semiStaticDirection; private RaycastHit hit; /// <summary> /// The delegate that will execute the current state of the FSM. /// </summary> private delegate void FState (); private FState stateMethod; /// <summary> /// Returns the vector of the current forward motion of the controller. /// </summary> /// <value> /// Returns a vector. /// </value> private Vector3 forward { get { return transform.TransformDirection (Vector3.forward); } } /// <summary> /// Helper function to get a right or left vector. /// </summary> /// <value> /// Returns left of right (Vector3). /// </value> private Vector3 randomLeftOrRight { get { return UnityEngine.Random.value > 0.5 ? Vector3.right : Vector3.left; } } /// <summary> /// Calculates the direction to the target object.
