Currently, as soon as a flow graph is deserialized, its units are “defined”, which means the code in the Definition method runs to create the required port objects based on the settings and the codebase. This is necessary because of the order of deserialization: because ports are not serialized, connections cannot be deserialized until the ports are created. Thus, definition has to run during deserialization, after units and before connections.
In a lot of cases, definition implies reflection. For example, an Invoke Member unit will reflect its deserialized data to find a matching MethodInfo, then analyze this MethodInfo to determine which input ports to create based on the parameters of the method.
While this has yet to be benchmarked to evaluate its impact, we know that reflection -- especially member fetching -- is slow, and that may be a cause of the initialization delay.
The problem is dual:
- Unity appears to deserialize (and define) all macros in the first frame, regardless of whether they are being used in the scene. This is unnecessary but unavoidable.
- For machine swapping to work in script generation, we need to deserialize the associated graph to fetch its data, but we don’t need it to be actually defined and reflected because we won’t execute it at runtime.
The proposed changes are:
- Rework the deserialization routine so that connections can be deserialized without ports
- Either create temporary invalid connections
- Or serialize ports (which may be beneficial for other cases, see Typing below)
- Remove Define from the deserialization routine
- Add an Initialize method to graphs and graph elements that calls Define for units
- Add an initialized boolean and an EnsureInitialized method
- Determine cases where initialization needs to be ensured and call EnsureInitialized:
- When a machine awakes, after the swap check, if we don’t swap
- When the graph context changes, before displaying the graph
- When generating C# scripts for a graph
- Initialize individual graph elements after they get added to a graph from the editor