We need the value returned from CreateInstance
to be consistent, it should always be the same type and have the same values otherwise we cannot detect the default values for our attribute overrides system.
Its worth pointing out that CreateInstance
is only used when creating the element from UXML, the purpose of this method is to do new T()
, there should not be any additional logic going on in here. If you want to have different versions of the class then this should be done through the UXML by setting the element attributes.
For example
<UXML>
<Department name="Dunder Mifflin" />
</UXML>
This would find the UxmlElement called Department
. It would use CreateInstance
to create a new default instance and then apply the overridden name
attribute to the new instance(using Deserialize
). This way we always get the same result from the UXML.
If you want to create different behaviours then you would either inherit from Department, use its attributes or add UxmlObjects support.
You can still have a constructor that takes parameters in your element, the default constructor is required for the UXML serialization but there’s no reason you cant have more for when you want to create them via script, such as for creating a singleton.
There is a draft of a blog post that goes into more details on the new UXML serialization system here.
I think you may be particularly interested in the UxmlObject feature, it sounds like it fits closer to your concept of factories and changing behaviours in elements. In your example I would make _adsManager
, _internetReachabilityManager
and _internetReachabilityManager
UxmlObjects. You can then customize the object reference.
Then you could change the behaviour through UXML, it could look like this:
<UXML>
<AdsButton>
<addsManager>
<MyCustomAddsManager/>
</addsManager>
</AdsButton>
</UXML>
or
<UXML>
<AdsButton>
<addsManager>
<MyDifferentCustomAddsManager some-value="something"/>
</addsManager>
</AdsButton>
</UXML>
These UxmlObjects can have different behaviours. They could have actions/events that could be subscribed to in the property set method, similar to your example.
You can also modify the element after creation via UXML, such as doing root.Q<MyElement>()
and then applying changes via script.