Data Binding
Note: This is a
Beta
feature, and is being actively developed. To use this feature, you needimporterVersion
to be set toBeta
.
Data binding allows sharing data from Unity with a template. This allows the template to access and use that data during generation.
Getting started
- Create a class to represent the data you wish to embed:
[CreateAssetMenu(menuName = "EmbedData")]
public class EmbedData : ScriptableObject
{
public List<string> Animals;
}
- Create an instance of this data in the Editor Project window (Right click -> Create -> EmbedData)
- Create a TT file to use this data:
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ import namespace="System.IO" #>
using System;
<#
foreach (var animal in Host.Data.Animals)
{
#>
[Serializable]
public class <#= animal#>Test {}
<#
}
#>
- Select the TT file in the Project window
- In the Inspector ensure
importerVersion
is set toBeta
- Drag the data instance you created in the Project window to the
embeddedData
section in the Inspector - Select "Apply"
This will cause the template to be run such that Host.Data
is the instance of your data.
Troubleshooting
Does the template need to be host specific?
Yes - to inform the template engine to use the host with our data, hostspecific
must be set to true
.
For instance:
<#@ template debug="false" hostspecific="true" language="C#" #>
Why does my template break when embeddedData is enabled?
If your template fails to generate content after embedding data, this may be because the data class you're using is complex, and references other types that the template environment is not aware of. Usually if this is the case, the error will inform you of what type is missing. You may specify this type in additionalTypes
list, or simplify your data class.
If you're not able to get it working, please open an Issue.
Why does my template break on first import?
If your data class and your codegen classes are in the same assembly (asmdef folder), on first import you may experience an error indicating the UnityEngine.Object
does not have required properties. This is because Unity wasn't able to generate the assembly with your data class before attempting the import - as such, your embedded data structure is missing.
The quickest solution is to move your data class to it's own assembly:
- Create a new folder
- Create an Assembly Definition in that folder
- Move the data class to this new folder
- Add a reference to this new assembly in the codegen assembly