Unity 3D

Posted by xeophin

Since I happen to be ranked somewhat high when it comes to mentioning Unity 3D and XML, and some of the posts1 happen to be outdated by now since I learned stuff2. But most of all, I intend to learn even more.

That's why I choose to release those two projects into the wild and publish them on github.


  1. Like the one on writing log files in Unity 3D or the one on getting strings out of XML files

  2. Yes, that happens from time to time. 

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 …

Posted by xeophin

(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;
}
Posted by xeophin

Finite State Machines are quite a convenient design pattern in Game Design, as they allow for quite some flexibility when programming AI behaviour.

Unfortunately, our first encounter with FSMs was poorly explained, and badly executed in ActionScript 3 using a bunch of switch statements – disregarding the fact that there would have been clearly more elegant solutions.

So, let's do the same for Unity 3D in C#, using delegates.

using UnityEngine;
using System.Collections;
 
public class FiniteStateMachine : Monobehaviour {
 
    // Create the delegate
    private delegate void FState ();
 
    // Create a holder for the delegate
    private FState stateMethod;
 
    #region UnityEngine methods
 
    /// <summary>
    /// Sets up the controller and puts the object into the new mode.
    /// </summary>
    void Start ()
    {
        stateMethod = new FState (EnterStateA);
    }
 
    /// <summary>
    /// Executes in every frame once. Only calls the current state method.
    /// </summary>
    void FixedUpdate ()
    {
        stateMethod ();
    }
 
    #endregion
 
    #region State A
 
    /// <summary>
    /// Sets up State A.
    /// </summary>
    private void EnterStateA () {
        // Things to prepare State A come here.
 
        stateMethod = new FState (StateA);
 
        // The next line will ensure that the first run of State A
        // will occur in the same frame.
Posted by xeophin

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.

Posted by xeophin

Just in case you are as stupid as I am and place the imported models in your Unity 3D scene and later realise that prefabs would have been rather fab: This is the solution: Drag your new prefab onto the old model in the hierarchy pane while having pressed alt – instant replacement. And once again, the day is saved.

Posted by xeophin

Today when working on my Unity3D game for Fantoche, I noticed it again: a short little squeak at the start of a triggered sound clip.

This has happened before in my prototype, but I chalked it off to my inferior post production skills when doing the first sound clips. The new sound clips, however, were pristine, I was sure of it.

So the problem had to be somewhere else. Changing a suspect in my trigger script did not change a thing.

Yet turning off 3D Sound in the Audio Importer Inspector did the trick: no more weird squeaks.1

Of course, there are situations where you would need the 3D Sound property set. I have yet to test this out. Maybe the squeak only occurred because my Audio Listener was so close to the Audio Source.


  1. Of course that meant turning it off for almost 60 clips by hand, since there is no such thing as bulk change in Unity ... *grml* 

Posted by xeophin

Placing stuff in 3D space in Unity 3D is simple, right? Just use this.transform.position and you are all set – or so we have been taught in art school. Turns out there are a few pitfalls I happen to hit whenever I work with that stuff.

Reading and Writing Values of transform.position

Yes, you can access the x, y, and z-values of the transform.position. But you can not change them directly (at least in C#). You have to use a Vector3 object, as in:

this.transform.position = new Vector3(newX, newY, newZ);

Obviously, by feeding the original values in, you can change just one value at a time:

this.transform.position = new Vector3(this.transform.position.x,
                                      newY, 
                                      this.transform.position.y);

Global vs. Local

Also of note: transform.position actually refers to the position in global space, it is the absolute position.

In many cases, you want to calculate movement relative to the parent object. In order to do this, you need to use transform.localPosition, which works exactly as the other one, but is calculated relatively to the position of the parent object. If there is no parent object, localPosition is the same as position.

In my opinion, it is in many cases better to use localPosition instead of position, since most of the time, you want to have objects move with or along their parent objects. After all, also the editor shows you the local position.

Posted by xeophin

Update

The code for this project has seen extensive changes and has since been migrated to GitHub. Read more about it over here – and then go forth and fork it. It is released under a Creative Commons License, so you are free to build upon it.

Since I already played around with XML in C#, this part of the project was easier to do than before.

What is it supposed to do?

Basically, I could simply hard-code most of my strings used in the game directly into the code – no one would notice the difference anyway. But obviously, this is not a very good idea, both because editing strings and later translating them becomes a pain.

Creating some data that would allow me to get strings out of an XML file would solve this problem – and, if the code is good enough, be reusable in later games.

It would allow me to edit text independently of the game code and add translations on a later date.



Navigation



Languages


Syndicate

Syndicate content