Automatic/Code Gen bind UGUI elements to a MonoBehaviour

Hey all, I come from Android development and we have a nice thing called “ViewBinding” which once a xml layout is defined, the compiler/toolset will generate a java class for us which we can then “inflate”/initialize and we’ll have every component defined on the xml as a property/field of the generated class.

Being the [SerializedField] hell one of my biggest complaints about building UI, I’ve been wondering if such feat is doable in Unity. Considering that there will be no nesting, unless a GameObject in the hierarchy is a prefab, the fields will be flatenned. so far I’ve observed:

  • A partial class extending MonoBehaviour attached to the component I want to generate the class with a custom Attribute, seems a good idea since the guid on the yaml still points to the class definition
  • I could parse the yaml looking for GameObjects and their fileIDs, each of these GO’s component would be a property on the generated class with its name normalized, the class for the property would be fetched from the m_script field guid using AssetDatabase.GUIDToAssetPath
  • After generating the fields I’d update the GO yaml in which the properties are defined to have them linked without relying on runtime code to run the links

One of the things I still couldn’t figure out (haven’t tried any of them though, just brainstorming) is how I’d generate the usings for the new class and how I’d parse the yaml files in a way to speed up things and also if I could add the generated class properties directly to the GO yaml without corrupting anything. And also I’m still trying to figure out how to find a GO’s yaml file from the code gen step…

Being that said, how would you approach the yaml parsing and the other issues I’ve raised? Or wouldn’t you even bother with that?

I managed to make it work… the only problem is when I try to account for nested prefabs, I hit a dead-end because just including the inner prefab does not make it show up with the stripped attribute I need… I could make it so nested prefabs need to be assigned manually but that’d kill the point of my tool.

Any ideas?

sfpe35