递归查找子物体+生命周期函数

递归查找子物体

相关代码:

cs 复制代码
    Transform FindChild(string childName, Transform parent)
    {
        if (childName == parent.name) {
            return parent;
        }
        if (parent.childCount < 1)
        {
            return null;
        }
        Transform obj = null;
        for(int i = 0; i < parent.childCount; i++)
        {
            Transform t = parent.GetChild(i);
            obj = FindChild(childName, t);
            if (obj != null)
            {
                break;
            }
        }
        return obj;
    }

在Unity上运行,例如:将该部分代码内容所在脚本挂载到 Cube (7)上,查找Cube (5):

cs 复制代码
    void Update()
    {
         Transform t = FindChild("Cube (5)", transform);
        if (t)
        {
            Debug.Log("t:" + t.name);
        }
       
    }

运行结果如下图:

Unity生命周期函数

相关代码:

cs 复制代码
    private void Awake()
    {
        Debug.Log("Awake");
    }
    /// <summary>
    /// 第二执行的方法
    /// 每次当前游戏物体激活都会被调用
    /// </summary>
    private void OnEnable()
    {
        Debug.Log("OnEnable");
    }
    /// <summary>
    /// 每次当前游戏物体失活都会被调用
    /// </summary>
    private void OnDisable()
    {
        Debug.Log("OnDisable");
    }
    /// <summary>
    /// 只会执行一次
    /// </summary>
    void Start()
    {
        Debug.Log("Start");
    }
    /// <summary>
    /// 物理更新写在这里面
    /// 更新频率是根据Fixed Timestep来的
    /// </summary>
    private void FixedUpdate()
    {
        Debug.Log("FixedUpdate");
    }
    // Update is called once per frame
    void Update()
    {
        Debug.Log("Update");
    }
    /// <summary>
    /// 在Update后执行,同样也是每一帧都会执行
    /// </summary>
    private void LateUpdate()
    {
        Debug.Log("LateUpdate");
    }
    /// <summary>
    /// 游戏物体被销毁时,先调用Disable,然后再调用OnDestory
    /// </summary>
    private void OnDestroy()
    {
        Debug.Log("OnDestroy");
    }

该系列专栏为网课课程笔记,仅用于学习参考。

相关推荐
weixin_424294671 小时前
程序不知道写在了什么位置???
unity
leo__5201 小时前
C# 虚拟键盘(软键盘)实现
单片机·c#·计算机外设
weixin_441940012 小时前
vuforia ar unity实验教程
unity·游戏引擎·ar
周杰伦fans3 小时前
AutoCAD C# 二次开发:如何精确监听工作空间切换事件
前端·c#
用户3721574261353 小时前
如何使用 C# 自动调整 Excel 行高和列宽
c#
妙为4 小时前
unreal engine5(UE5)中使用Rider
ue5·游戏引擎·虚幻·rider
AI导出鸭PC端4 小时前
智谱清言怎么生成word文档?AI导出鸭终结乱码烦恼
人工智能·ai·c#·word·豆包·ai导出鸭
xiaoshuaishuai85 小时前
C# AvaloniaUI 中旋转
开发语言·c#
WarPigs5 小时前
Unity AB包资源加载管理器
unity
weixin_428005305 小时前
C#调用 AI学习从0开始-第2阶段(Function Calling+工具调用智能体)-第9天实战-实现计算器工具
开发语言·学习·c#·functioncalling·ai实现计算器工具