Home > Mobile >  Unity Add callbacks to prefab objects dynamically in code
Unity Add callbacks to prefab objects dynamically in code

Time:01-31

I am creating a canvas with a table containing TextmeshPro Input fields on a row. 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).

There will be many Rows on this canvas and the number of rows can vary according to the data they look up. So they have to be added dynamically

The input fields are part of a GameObject collection. 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.

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. Can this be done or is this the wrong approach?

Mark

CodePudding user response:

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. 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!

  • Related