Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question CreateInstance<VisualTreeAsset>() and Save it as an Asset at path?

Discussion in 'UI Toolkit' started by QuebecDev, Jan 1, 2023.

  1. QuebecDev

    QuebecDev

    Joined:
    May 9, 2020
    Posts:
    37
    Hi

    I am having trouble saving an instance of VisualTreeAsset to 'Assets/'

    I had an error: CreateAsset() should not be used to create a file of type '' - consider using AssetDatabase.ImportAsset() to import an existing '' file instead or change the file type to '*.asset'. This error will in a future release be changed to an exception.

    When I fix that error by doing AssetDatabase.CreateAsset(visualTree, $"{path}/{name}.asset"); asset gets created successfully, BUT when I try to open the Uxml the UI Builder throw errors:

    No1.
    Exception thrown while invoking [OnOpenAssetAttribute] method 'Unity.UI.Builder.Builder:OnOpenAsset (int,int)' : ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index

    No2.
    ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index

    How can I CreateInstance<VisualTreeAsset>() and Save it as an Asset at path? Because the CreateInstance<VisualTreeAsset>() way, doesn't work for this type.

    Code (CSharp):
    1.             var path = Path.GetDirectoryName(AssetDatabase.GetAssetPath(this));
    2.             var assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
    3.  
    4.             if (visualTree == null)
    5.             {
    6.                 var visualTree = CreateInstance<VisualTreeAsset>();
    7.                 visualTree.name = name;
    8.  
    9.                 AssetDatabase.CreateAsset(visualTree, $"{path}/{name}");
    10.              
    11.                 this.visualTree = visualTree;
    12.             }
     
    Last edited: Jan 2, 2023
  2. QuebecDev

    QuebecDev

    Joined:
    May 9, 2020
    Posts:
    37
    Bump. How can we create instance and save a VisualTreeAsset properly? Because the way shown above creates half of a VisualTreeAsset.
     
  3. marco-vidaurre

    marco-vidaurre

    Joined:
    Dec 15, 2012
    Posts:
    7
    I think you would probably need to just write out a uxml instead of trying to save it as a Unity asset.