Category Archives: C#

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");
}

c# Jagged Arrays

While working on a new game app, I needed to initialized a multi-dimensional array upon declaration.  I initially used a two dimensional array declared as such:

readonly TrackType[,] validTypes = {{TrackType.none},
{TrackType.one, TrackType.two, TrackType.three}};

This worked fine and the array was declared and initialized correctly.  I then decided I wanted to extract a row from this array and work on it, rather than always using two indexes as I processed the entries.  However, with a multi-dimensional array it’s not possible to do this implicitly.  The solution was to create a Jagged Array.  Each element is accessed in a similar way, but it allows you to grab a pointer to a row of the array, which is what I wanted.

The syntax for defining and initializing it during declaration is quite different however, and this is what I ended up with:

readonly TrackType[][] validTypes = new TrackType[][] {
new TrackType[] {TrackType.none},
new TrackType[] {TrackType.one, TrackType.two, TrackType.three}};

More typing, but it gets the job done.

Learning C# Syntax

I was never ‘taught’ c# – I’ve grown into it from other languages and there are certain nuances and quirky syntax that I might have read/seen at one point or another, but forgotten.  It’s with that in mind that I’m sharing this recent ‘discovery’ by me.

C# has a ?? operator.  It’s kind of like the standard conditional operator ?: but is specifically setup as a null check shortcut.

These two sections of code are functionally equivalent

	parentToggle = gameObject.GetComponent();
	if (parentToggle==null)
		parentToggle = gameObject.GetComponentInParent();
	parentToggle = gameObject.GetComponent() ?? gameObject.GetComponentInParent();

In other words, ‘arg1 ?? arg2’ is the same as saying return arg1, unless arg1 == null in which case return arg2.

You could also use ‘arg1!=null?arg2:arg1’ but the ?? pattern is less typing 🙂