Programming

Posted by xeophin

Yes, this is yet another C#-in-Unity3D post. I hope you will forgive me ;)

Up until now, I would usually reference other GameObjects or components like this:

public class Foo : MonoBehaviour {
 
    public Bar b;
 
    void Start () {
        b = GameObject.FindObjectByTag("Player").GetComponent<Bar>();
    }
}

This works fine until you suddenly want to access a GameObject without knowing if it is already there.

My first solution would have been to rewrite the whole thing as a property:

public class Foo : MonoBehaviour {
 
    public Bar b {
        get {
            return GameObject.FindObjectByTag("Player").GetComponent<Bar>();
        }
    }
}

Of course, since there is no caching mechanism on the compiler level, this "solution" comes at a huge performance cost. The real solution: adding our own caching mechanism.

public class Foo : MonoBehaviour {
 
    private Bar _b;
    public Bar b {
        get {
            if (_b == null) { 
                _b = GameObject.FindObjectByTag("Player").GetComponent<Bar>();
            }
            return _b;
        }
    }
}

Of course, this pattern allows for even more sophisticated mechanisms, like fetching new data once the underlying object has changed, but getting the cached version in all other cases.

Thanks to UnityAnswers, that got me that answer so fast.

Posted by xeophin

Animation curves in the new Unity 3 can not only be used for animation, but can be directly accessed by scripts.

By defining

AnimationCurve curve;

you can add a specific curve to the script in the editor. Using AnimationCurve.Evaluate() you can get the y value at a specific time. Using those curves, you are no longer limited to use Lerp() at every corner (or one of the additional functions provided by Mathfx).

Thanks to Mario von Rickenbach who mentioned that in a lesson as an aside …



Navigation



Languages


Syndicate

Syndicate content