ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

FirstChildOrDefault

Finds first occurrence of a Unity Transform that satisfies the predicate

Source

using System;
using UnityEngine;

public static class TransformEx
{
    public static Transform FirstChildOrDefault(this Transform parent, Func<Transform, bool> query)
    {
        if (parent.childCount == 0)
        {
            return null;
        }

        Transform result = null;
        for (int i = 0; i < parent.childCount; i++)
        {
            var child = parent.GetChild(i);
            if (query(child))
            {
                return child;
            }
            result = FirstChildOrDefault(child, query);
        }

        return result;
    }
}

Example

var cube = this.transform.FirstChildOrDefault(x => x.name == "deeply_nested_cube");

Author: Loek van den Ouweland

Submitted on: 25 apr. 2018

Language: C#

Type: Transform

Views: 3715