Search Unity

Adding existing objects to with AssetDatabase.AddObjectToAsset

Discussion in 'Asset Database' started by Tymianek, Nov 19, 2020.

  1. Tymianek

    Tymianek

    Joined:
    May 16, 2015
    Posts:
    97
    I have multiple existing ScriptableObject Assets in the Resources folder.
    I want to Add two of them into the third one, and have a similar structure to the default button animator
    upload_2020-11-19_21-3-15.png

    I tried different methods, but couldn't get it to work. I tried to AddObjectToAsset, but it already is added into project, so it produces an error. I tried to MoveAsset into a second asset, but it doesn't work either. I tried some weird things, like the example below, without any luck.
    Code (CSharp):
    1. AssetDatabase.MoveAsset(
    2.      AssetDatabase.GetAssetPath(myAsset2),
    3.     AssetDatabase.GetAssetPath(myAsset) + $"/{myAsset2.name}.asset"
    4. );
    What is a proper way to add one asset that is already in the project to another asset that is already in the project?
     

    Attached Files:

  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    I don't think Unity supports that relationship. You can put a bunch of assets together into a single asset, but each one of those assets is an asset in its own right.

    You see this most commonly when you import a texture as a sprite: it's a texture, but it also has a sprite inside it. Other examples are FBX files, which may have bunches of GameObjects and/or Meshes in them.

    The only other alternative is the obvious and most common one, to create your composite asset with references to the other assets that make it up.
     
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,011
    You most likely have to duplicate the object before you add it to your asset. An asset that is already persisted in its own asset file can not be saved to another one. Try using Instantiate on your asset first and add the clone to your asset. When that works you can delete the other standalone asset.
     
    eses likes this.
  4. Tymianek

    Tymianek

    Joined:
    May 16, 2015
    Posts:
    97
    And then I need to remap all references to the asset in the project.