首页 > 解决方案 > 如何观察添加子游戏对象并使用 UniRx 获取它?

问题描述

首先,请看我的代码。

using UniRx;
using UniRx.Triggers;
....... 
        var parent = new GameObject("parent");
        parent.OnTransformChildrenChangedAsObservable()
            .Subscribe(_ =>
            {
                Debug.Log("child object is added");
            });
        var child = new GameObject("child");
        child.transform.SetParent(parent.transform);

当我设置孩子的父母时,肯定会调用 OnTransformChildrenChangedAsObservable() 。但是,我不知道如何获取添加的对象,因为参数“_”是 Unit,而不是 GameObject。
这就是我真正想做的事情。

        parent.OnTransformChildrenChangedAsObservable()
            .Subscribe(g =>
            {
                Debug.Log(g.name);
            });

有没有办法实现这一点?事实上,我对是否使用 UniRx 并不特别。
谢谢!

标签: c#unity3dunirx

解决方案


目前,它似乎已经解决了。首先,我准备了一个函数作为 GameObject 的 Extension,以获取它自己的子对象,例如:

        public static List<GameObject> GetChildrenObjects(this GameObject gameObject)
        {
            var childrenObjects = new List<GameObject>();
            foreach (Transform child in gameObject.transform)
            {
                childrenObjects.Add(child.gameObject);
            }
            return childrenObjects;
        }

所以现在我可以得到最后添加的子对象,如下所示。

        parent.OnTransformChildrenChangedAsObservable()
            .Subscribe(_ =>
            {
                var added = parent.GetChildrenObjects().Last();
            });

推荐阅读