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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How would I go about serializing a reference to an asset?

Discussion in 'Scripting' started by Sabo, Jan 20, 2017.

  1. Sabo

    Sabo

    Joined:
    Nov 7, 2009
    Posts:
    151
    I am trying to save references to assets during runtime. Serializing them using the JsonUtility only saves their instance id, which changes with each session and thus will not work for saved game data. How would I save a "true" reference to an asset?

    Or maybe I am approaching this from the completely wrong point of view. I have an inventory system, with each slot having a reference to an asset and a stack count. I figured it was a decent way of doing things, with a single asset containing "asset data", including icon(s), sound(s) and what have you, which can be used multiple times by simply combining the asset with a stack count. Maybe there are better options out there?
     
  2. mikael_juhala

    mikael_juhala

    Joined:
    Mar 9, 2015
    Posts:
    247
    One of our games also has an inventory with a bunch of items. Data of each item is defined in a ScriptableObject asset. When the game is saved, it only writes the name of the asset into a JSON file. And when the game is loaded again, the actual assets are fetched according to the names. So we're not saving an actual reference, only its name. Additional data, such as a stackcount, can of course be saved along with the name.
     
  3. Sabo

    Sabo

    Joined:
    Nov 7, 2009
    Posts:
    151
    If that is the way to do it, I am ok with that. How would you recommend one would go about it? Place the assets in a Resource folder and use the ".name" of each asset when serializing the data, then use that info to dynamically load the asset from the Resource folder?
     
  4. mikael_juhala

    mikael_juhala

    Joined:
    Mar 9, 2015
    Posts:
    247
    Yeah, that should work just fine.