Trying to create random encounters with percents
I am currently working on a turn-based RPG. I have all my enemies programmed as [SerializedFields] in their own enemy file. This way I can add in enemies and edit their stats easily. I want to add a percentage as [SerializedFields] as well to these enemies. I want to be able to have my character encounter them randomly as he walks around but with different percents. For example, random encounter happens Enemy A has 60% chance, Enemy B has 30% chance and Enemy C has 10% chance. Currently, I only encounter just Enemy A as he is hardcoded in.
This is my current code and I am not sure where to go from here in order to encounter the other enemies with the proper percent chance. Any help in moving me in the right direction would be very much appreciated.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
public class StarterArea : MonoBehaviour
{
[SerializeField] List<Enemy> wildEnemy;
public int[] chance =
{
60,
30,
10
};
public int totalchance;
public int randomchance;
public Enemy GetRandomWildEnemy)
{
foreach(var item in chance)
{
totalchance += item;
}
randomchance = Random.Range(0, totalchance);
for(int i=0; i<chance.Length; i++)
{
if (randomchance <= chance[i])
{
return;
}
else
{
randomchance -= chance[i];
}
}
}
}
Answer by johnanthonyjubilo · Apr 13, 2021 at 12:12 PM
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
public class StarterArea : MonoBehaviour
{
[SerializeField] List<Enemy> wildEnemy;
public int[] chance =
{
60,
30,
10
};
public int enemyAchance;
Public int enemyBchance;
Public int enemyCchance;
Void start(){
enemyAchance = random.value(0, 100)
enemyBchance = random.value(0, 100)
enemyCchance = random.value(0, 100)
}
public Enemy GetRandomWildEnemy)
{
foreach(var item in chance)
{
totalchance += item;
}
randomchance = Random.Range(0, totalchance);
for(int i=0; i<chance.Length; i++)
{
if (enemyAchance > chance[0])
{
return;
} else if (enemyBchance >chance[1])
{
return;
} else if (enemyCchance > chance[2])
{
return;
}else{
Retern null;
}
}
}
}
Here is the code for your enemy random spawn