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 Load specific ScriptableObject in runtime by its ID

Discussion in 'Scripting' started by Pietrofonix, Jun 14, 2022.

  1. Pietrofonix

    Pietrofonix

    Joined:
    Aug 1, 2020
    Posts:
    54
    Hi guys, i'm trying to save weapons gameobjects into a file. One way I was thinking, is by serializing (save) only the ID of the weapon created inside its ScriptableObject, and then deserialize it (load) that ScriptableObject in runtime. The problem is that I don't know how to load ScriptableObjects from the assets. How can I get a ScriptableObject with a specific ID, and then load it by searching through all the ScriptableObjects in a folder? I was trying with the Resources folder, but it's not recommended by unity and it wouldn't work because I can't access the ID variable inside the ScriptableObjects.

    This is the script of the ScriptableObject:

    Code (CSharp):
    1. [CreateAssetMenu(menuName = "ScriptableObjects/Weapon")]
    2. public class WeaponDataSO : ScriptableObject
    3. {
    4.     public string ID;
    5.     public GameObject WeaponPrefab;
    6.     public string Name;
    7.     public float Damage;
    8.     public float FireRateRPM;
    9.     public int MaxBulletsMagazine;
    10.     public bool SemiAuto;
    11.     public bool FullAuto;
    12.     public AudioClip ShootSound;
    13.  
    14.     public enum WeaponTypes
    15.     {
    16.         Rifle,
    17.         SMG,
    18.         Pistol
    19.     }
    20.  
    21.     public WeaponTypes Type = WeaponTypes.Rifle;
    22. }
     
    Last edited: Jun 14, 2022
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,882
    You've got the right idea to serialise out just the ID and use that to look them up.

    Basically you want to make a rudimentary database for your items. This can be as simple as another scriptable object that holds a reference all SO's of a particular type. You save out the ID's, and then when loading, you look up the ID's in the database to restore the data.

    Lots of ways this can be accomplished.
     
  3. dlorre

    dlorre

    Joined:
    Apr 12, 2020
    Posts:
    700
    Maybe use addressables?
     
  4. Pietrofonix

    Pietrofonix

    Joined:
    Aug 1, 2020
    Posts:
    54
    I found out about addressables when I was looking for this problem. I've never used them and I have to study them before. In particular I have to see how can I use them with ScriptableObjects
     
  5. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,882
    Addressables won't help in this situation. It's designed for streaming content in and out of memory. You still need the SO in memory to see what it's ID is.