Search Unity

Is it good practice to keep certain data in a separate class/struct?

Discussion in 'Scripting' started by Shack_Man, Jan 20, 2019.

  1. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    372
    Is it bad practice and/or bad for performance to keep variables within a second class? For example if I have a class "EnemyManager" and this class keeps track of things like number of enemies, how many have been spawned etc. it would make saving the game a lot easier to just make a second class, a non-monobehaviour, call it enemyManagerData and keep everything in there.

    When the EnemyManager is instantiated, it will create a data class:

    Code (CSharp):
    1.     void Awake()
    2.     {
    3.         enemyData = new EnemyData();
    4.     }
    Now every time another Object/script wants to know something about the current enemy data, it would have to access it like this: enemyManager.enemyManagerData.enemiesSpawned.


    Is that bad practice? Why isn't this standard? it keeps things clean and saving and loading becomes so much easier, I can just serialize the EnemyManagerData class with Json and don't have to do go through the variables and assign each to the enemyManager.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,735
    This is good practice, generally speaking. Serializing a lightweight POCO is always going to give you less headache, plus you can just get a handle on where your data needs to be saved/loaded better.

    Look into ScriptableObjects too... they are AWESOME for configuring your game. They are basically "bags of data" that are editable in the Unity inspector.

    Generally the pattern is to use ScriptableObjects for configuration data, data that you set in editor to control game behavior. And then you use a data object (or collections thereof) to store the mutable data as your game runs.

    As for load/save, putting the constructor for your data in Awake() is one approach.

    But then think about how you are going to go about making all those objects afresh during a "GameLoad" event. Keep in mind there may be more enemies than started in your scene initially.

    It may be easier to go after a factory pattern, whereby an enemy factory can take null for enemyData and make a fresh enemy, or it can take an enemyData and create a partially-used worn-out beat-up enemy, and that lets you centralize all the code for each type of enemy.
     
    Shack_Man likes this.
  3. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    372
    Great advice as always! I am currently learning about Scriptable Objects beyond the standard, there are these 2 fantastic talks on the Unity Channel. I've only briefly glanced over the factory method, I wasn't sure what would be so great about it but now I see, I bumped it up on my to do list.
    Thank you!
     
    Kurt-Dekker likes this.