Category Archives: Unity3d

LINQ, C# and Unity…

Having never ‘learned’ c#, the LINQ syntax sometimes escapes me, and it takes a bit of getting used to, but honestly, it’s worth the price of admission!  I recently needed to find the first object in a list whose Y value was greater than another Y value (basically making sure it was on screen).

My first thought was to use a foreach loop, with a break and a bool flag along with a var to store the index like so:

       bool found = false;
       int rowIndex = 0;

                foreach (float y in rowYPos)
                {
                    if (y>scrollOffset)
                    {
                        found = true;
                        break;
                    }
                    rowIndex++;
                }

This code works, and will return the index of the first entry that exceeds scrollOffset;

However, with LINQ all that becomes:

            int firstRowIndex = rowYPos.FindIndex(x=>x>scrollOffset);

Much shorter, less local vars and pretty self-explanatory.  I didn’t benchmark it to see which was faster, though my hope is that the LinQ method would be, It’s not something that happens often enough to make it a worry.

Handy tip: You’ll need to add a using System.Linq; to the start of the file…

Useful transform property

I was messing around with an idea for a mobile game with Unity, and need to move a character in the direction it was facing.  I’ve done this before by generating a unit vector from the Y angle (it’s a top down view) using sine/cosine.  However, during a hunt for something unrelated, I found:

        playerTransform.localPosition += playerTransform.forward * velocity * Time.deltaTime;

Where, velocity is the speed the player is moving.  Turns out the transform.forward property returns the vector based on the direction of the transform, no more messy code 😀

 

Removing all children from a Transform

I updated my remove all children code to make it less error-prone.  I was having an issue with the children being deleted before the for loop completed, which left some behind.  Using LINQ I was able to adjust it to make a copy of the list of children before I called destroy:

    public static void DestroyAllChildren(Transform parent)
    {
        if (parent!=null)
        {
            List<Transforml = parent.Cast<Transform>().ToList();
            foreach (Transform c in l)
            {
                if (c!=null && c.gameObject!=null)
                {
                    if (c.childCount>0)
                        DestroyAllChildren(c);
                    Destroy(c.gameObject);
                }
            }
            parent.DetachChildren();
        }
    }

Calling parent.DetachChildren() removes the children from the parent immediately.

Simple Action Hooks

If you need to add a simple hook that can be subscribed to and then called when something specific happens, you can do it with System.Action.

For example, I needed a few objects to be notified when the player would enable or disable certain features using a toggle checkbox.  In the class managing the UI I added the following line:

    public static System.Action OnEnabledChanged;

When the toggle was changed by the player, the following code is executed:

            if (OnEnabledChanged!=null)
                OnEnabledChanged();

In each of the other objects that needed to be notified of this event, I then added the following line:

        UIManager.OnEnabledChanged += onEnabledChanged;

where onEnabledChanged is a local function that is called when the UIManager responds to the player tapping on the checkbox.  The event can be subscribed to by multiple objects, though the only caveat is to make sure if a subscribed object is destroyed it unsubscribes from the event by using:

        UIManager.OnEnabledChanged -= onEnabledChanged;

Or you’ll start getting errors.

If you need to pass a parameter to your subscribed events, then you can do so with a simple modification:

    public static System.Action<bool> OnEnabledChanged;

and

            if (OnEnabledChanged!=null)
                OnEnabledChanged(isEnabled);

Your subscribed functions will now need to accepted a bool parameter (for example).

OnDisable & OnApplicationQuit

In my latest project, I ran into an issue with OnDisable being fired when I stop the project running in the editor.  I’d get a host of errors about destroying transforms and not gameobjects.  Now I didn’t do any of that, but I did have an OnDisable routine that moved all the children of the disabled gameobject into a pool for reuse at a later point.

Turns out that all GameObject’s are disabled when you exit run mode in the editor, and they all have OnDisabled called one last time.  Not sure why this caused the error I was seeing and not even sure it was a real problem, but it was ugly seeing all those red exception errors fill my console window.

OnApplicationQuit to the rescue! After some googling I found that others have been having the same problem and it is a pretty simple solution.  Just add a private bool to your script and the Monobehavior method ‘void OnApplicationQuit()’ which just sets this bool to true.  Now in your OnDisabled method you can check to see if that bool is true & do nothing if it is!

OnApplicationQuit is called before the OnDisabled methods, so that flag gets set and your other methods just return. Simple & Clean!

private bool applicationIsQuitting;
void OnApplicationQuit()
{
	applicationIsQuitting = true;
}
void OnDisabled()
{
	if (applicationIsQuitting)
		return;
	Debug.Log("OnDisabled");
}