Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Best practice for saving and loading enemies with IDs?

Discussion in 'Editor & General Support' started by kcfos, Apr 12, 2021.

  1. kcfos

    kcfos

    Joined:
    May 20, 2018
    Posts:
    16
    Here is my pain:

    Right now all my enemies have an 'EnemyIndex' int and I have an array of enemyPrefabs. Whenever I save an enemy I save this int, and when I load, I create an instance from my enemyPrefab array based on the loaded index.

    Every time I want to create a new enemy for my game I have to:
    • Figure out what the current highest enemyIndex is
    • Set my new enemy's index to that number + 1
    • Edit my array of enemy prefabs with my new enemy

    I feel like this is a waste of time and could be easier.
    This same issue occurs for items as well, anything that I would like to save/load different types of.

    How can I minimize my work when adding new content?
    Is there anyway I can avoid having a big array of enemies?
    Is there a way I could automatically give a new enemy type a proper id?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,519
    If you're talking about a runtime ID, just generate it with an ever-increasing integer at load / instantiate time.

    If you're writing this ID to disk with the asset, I'm not sure that is the best approach: everything on disk already has a unique file path, so generally I like to use that as my primary asset index key.

    Of course that means if you rename or move a prefab, those values change, potentially invalidating save games. But this can be addressed simply by never renaming or moving assets once they are published.

    You can always leave them in the scene and get them whenever you need. But it has to be somewhere, and when you need access, you need to get them. Not sure there's a way around that. SOMEBODY has to know about it, either Unity with scene objects, or your own arrays/lists.
     
    kcfos likes this.