简体   繁体   English

Unity 在代码中动态添加预制对象的回调

[英]Unity Add callbacks to prefab objects dynamically in code

I am creating a canvas with a table containing TextmeshPro Input fields on a row.我正在创建一个 canvas,其中包含一行包含 TextmeshPro 输入字段的表。 I'm using the XR Input System for the Oculus Quest Vr Headset and wish to handle input from the controllers so they can interact with the Input fields (Select and DeSelect).我正在为 Oculus Quest Vr 耳机使用 XR 输入系统,并希望处理来自控制器的输入,以便它们可以与输入字段(选择和取消选择)交互。

There will be many Rows on this canvas and the number of rows can vary according to the data they look up.这个 canvas 上会有很多行,行数可以根据他们查找的数据而变化。 So they have to be added dynamically所以他们必须动态添加

The input fields are part of a GameObject collection.输入字段是 GameObject 集合的一部分。 I've created a prefab for this collection.我为这个系列创建了一个预制件。 I modified the prefab by placing it in a scene.我通过将预制件放置在场景中来修改预制件。 Assigned to the GameObject the Callback scripts for "On Select" and "On DeSelect" and updated the prefab.为 GameObject 分配了“On Select”和“On DeSelect”的回调脚本,并更新了预制件。

When I check the updated prefab, I see that it has lost the callback references.当我检查更新后的预制件时,我发现它丢失了回调引用。 So I assume they need to be added in code after the GameObject has been instantiated.所以我假设它们需要在 GameObject 实例化后添加到代码中。 Can this be done or is this the wrong approach?可以这样做还是这是错误的方法?

Mark标记

Ok, so I've found a solution to my own question.好的,所以我找到了解决我自己问题的方法。

I've created a script in the root prefab object. The child callback then references the root prefab and relevant functions within the prefabs said script.我在根预制件 object 中创建了一个脚本。子回调然后引用根预制件和预制件中所述脚本中的相关函数。 The code in the root script can pass reference or search for any global gameobjects that need to be aware of the interaction and call their callbacks.根脚本中的代码可以传递引用或搜索任何需要了解交互并调用其回调的全局游戏对象。

The script is automatically saved along with the prefab and accessible for every instantiation.该脚本会与预制件一起自动保存,并且每个实例都可以访问。

Problem solved!问题解决了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM