Hi.
I’ve been working on a game with random based levels. I got a script which creates blocks (which represent the floor), coins and enemys. The chance for spawning the various things alters over time. Basically I define some breakpoints for the probability and betwenn those the current chance gets calculated. The script works fine but it is not very clean right now and if I wanted to add another spawnable gameObject, like a new kind of block, I’d have to go through half my script and add trivial lines and resize some arrays. I’m also planning an upgrade system and from what I can predict i would be running into the same problems there too.
My Question is: is there a way of keeping my code more clean, maintainable and expandable?
Thank you
Here are some snipets of my code:
[System.Serializable]
public class SpawnChanceCoins{
public float startDistance;
public float smallCoinChance;
public float smallCoinRowChance;
public float mediumCoinChance;
public float mediumCoinRowChance;
public float bigCoinChance;
public float bigCoinRowChance;
}
[System.Serializable]
public class RandomVariables {
public int minBlockLength = 2;
public int maxBlockLength = 8;
public int minGapLength = 2;
public int maxGapLength = 8;
public SpawnChanceCoins[] coinChances;
public chanceCalculationMethod coinCalculationMethod;
// more arrays of chances for blocks and enemys
public enum chanceCalculationMethod { instant, linear, smooth}
public void SortCoinChances () {
for(int j = 0 ; j < coinChances.Length -1; j++){
for( int k = j + 1 ; k < coinChances.Length; k++){
if(coinChances[j].startDistance == coinChances[k].startDistance)
Debug.LogError("Two coinchances have the same startDistance!");
}
}
System.Array.Sort(coinChances, delegate(SpawnChanceCoins c1, SpawnChanceCoins c2) {
return c1.startDistance.CompareTo(c2.startDistance);
});
}
//Same function for blocks and coins
//Here comes the ugly part:
public float[] CalculateCoinChances (float distance){
float[] output = new float[6];
if(distance < blockChances[0].startDistance){
output[0] = coinChances[0].smallCoinChance;
output[1] = coinChances[0].smallCoinRowChance;
output[2] = coinChances[0].mediumCoinChance;
output[3] = coinChances[0].mediumCoinRowChance;
output[4] = coinChances[0].bigCoinChance;
output[5] = coinChances[0].bigCoinRowChance;
} else {
//here is a switch for coinCalculationMethod in order to calculate the chance between the breakpoints.
// All in all you'll find the six lines from above four more times with another expression behind the =.
}
return output;
}
}
public class FloorCreator : MonoBehaviour {
public RandomVariables rnd = new RandomVariables();
[System.NonSerialized]
public float[] currentCoinChances;
IEnumerator Start (){
currentCoinChances = new float[6]; //I'd have to chance this by hand if i wanted to add more coins
//same goes for blocks and enemys;
}
//deep into the code:
currentCoinChances = rnd.CalculateCoinChances(Statics.distance);
}