Search Unity

Idle rpg (character stats)

Discussion in 'Scripting' started by Oleksa1, Jan 23, 2020.

  1. Oleksa1

    Oleksa1

    Joined:
    Jan 23, 2020
    Posts:
    2
    Hi all, i have a question about code design.
    So l want to spawn 10 heros (5 vs5) and have method which do this . This method accepts 5 main parameters ( hp, damage, armor, etc) But if i need more than 20 parameters how to do this right.
    The structure like
    Spawnhero(hp ,armor, dam,....and +20 paramets ) іsnt comfortable or i am wrong?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Where does the information come from in the first place? Are you hardcoding it into your scripts or loading it from somewhere?

    If you don't have a plan for this yet, you probably want to use JSON files to store the data, with JsonUtility (builtin, simple to use) or LitJson (supports dictionaries and lists) to read the data into an instance of a class that holds the data. It's this class which you'll pass as a parameter into your spawning method.
    Code (csharp):
    1. [System.Serializable]
    2. public class HeroData {
    3. public int HP;
    4. public int damage;
    5. //etc
    6. }
    7.  
    8. public TextAsset someHeroJSONFile;
    9. ...
    10.  
    11. HeroData thisHeroData = JsonUtility.FromJson<HeroData>(someHeroJSONFile.text);
    12. YourSpawnMethod(thisHeroData);
    13.  
    14. ....
    15. public void YourSpawnMethod(HeroData thisHero) {
    16. ...
     
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    If you have a large collection of related variables that you tend to use together, you should consider creating a "class" or "struct" to hold them all so that you can pass them around like a single variable.

    (Although creating a function with 20 parameters is perfectly legal if you really decide that's the most convenient thing to do.)