c# - 如何观察添加子游戏对象并使用 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 并不特别。
谢谢!
解决方案
目前,它似乎已经解决了。首先,我准备了一个函数作为 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();
});
推荐阅读
- css - 数据表中水平滚动中的标题修复问题
- python - 每组熊猫相对于特定行的百分比变化
- stripe-payments - 仅当 Stripe 支付有效时才注册用户
- json - 在 Azure Synapse 中读取 JSON
- azure - Azure B2 - jit 迁移无法在密码重置时对用户进行身份验证 - 全部使用自定义策略配置
- arrays - 使用不同的值更新MongoDB中数组内的多个对象值而不循环,但纯查询
- excel - LabVIEW运行时不保存到Excel
- javascript - nuxt blob 中的 Openlayers 未定义
- c - 为什么我不能使用“%[^\n]”扫描集?
- javascript - Cloud Functions 在模拟器中工作,但在部署时不工作