Since you’re just getting into scripting, now is the perfect time to tackle working with data files. (Whenever possible, keep your code and data separate.) You could use ScriptableObjects or something similar, but I think a simple text file is the best way to start.
Two easy text formats are comma-separated values (CSV) and JSON. Your CSV file might look something like this:
#chance, monster, hp, tohit, damage
50, goblin, 5, 25, 3
80, orc, 10, 40, 5
100, ogre, 18, 45, 8
The way I chose to format the file above, the random encounter is a goblin if a d100 die roll is 00-50. The goblin has 5 HP, hits 25% of the time, and does 3 damage. If the d100 roll is 51-80, the encounter is an orc who has 10 HP, hits 40% of the time, and does 5 damage.
In Unity, text files in your project are treated as TextAssets, the contents of which are in TextAsset.text. You can use the String.Split method to split it on newlines (“\n”) to break out each line, and then again on commas (“,”) to get each field in the line.
JSON is more awkward to edit unless you use a JSON editor instead of a plain text editor. But Unity’s JsonUtility class makes it easy to read. Your JSON text file might look like this:
{
encounters : [
{ "chance":50, "monster":"goblin", "hp":5, "tohit":25, "damage":3 },
{ "chance":50, "monster":"orc", "hp":10, "tohit":40, "damage":5 },
{ "chance":50, "monster":"ogre", "hp":18, "tohit":45, "damage":8 },
]
}
And you could read it in a class like this:
using UnityEngine;
using System;
[Serializable]
public class Encounter {
public int chance;
public string monster;
public int hp;
public int tohit;
public int damage;
}
[Serializable]
public class EncounterList {
public Encounter[] encounters;
}
public class CombatManager : MonoBehaviour {
public TextAsset dataFile; // Assign in inspector.
private EncounterList encounterList;
void Awake() {
// Read the data file:
encounterList = JsonUtility.FromJson<EncounterList>(dataFile.text);
}
// Choose a random encounter:
public Encounter ChooseRandomEncounter() {
var roll = Random.Range((int)0, (int)100);
foreach (var encounter in encounterList.encounters) {
if (roll <= encounter.chance) return encounter;
}
return null;
}
}
The script above shows how to read a data file and choose a random encounter. It doesn’t cover how to run the random encounter, but the previous replies sketched it out pretty well. If you get stuck on that part, post back and I’m sure some of us may have some suggestions.