public void SpawnMonster() { // First calculate where to spawn it. Tile spawnTile = null; int attempts = 0; int x = 0; int y = 0; // Keep calculating new places to spawn until either exceed the maximum amount of attempts allowed, or you find a valid spawn tile which isn't water. while ((spawnTile == null || spawnTile.tileType == TileType.Water) && attempts < maxSpawnAttempts) { // Get a random direction. Vector2 dir = (Vector2)Random.onUnitSphere; dir = dir.normalized; // Get a random distance. float distance = Random.Range(minSpawnDistance, maxSpawnDistance); dir *= distance; // Figure out the closest tile. x = GameController.instance.player.x + Mathf.RoundToInt(dir.x); y = GameController.instance.player.y + Mathf.RoundToInt(dir.y); // Get that tile. spawnTile = GetTileAt(x, y); attempts += 1; } // If we failed to find a spawn tile, abort! if (attempts >= maxSpawnAttempts) { return; } // Now figure out which monster to spawn based on the biome. // Generate a random number between 0 and the sum of the weights for this biome. float sumOfWeights; biomeEnemySpawnWeightSum.TryGetValue(spawnTile.tileType, out sumOfWeights); float r = Random.Range(0f, sumOfWeights); // Sum through all the monster's weights until the sum is more than the random number generated. EnemyType enemyType = null; float sum = 0f; foreach (EnemyType eT in EnemyType.enemyTypes) { float weight; eT.spawnWeights.TryGetValue(spawnTile.tileType, out weight); sum += weight; if (sum > r) { enemyType = eT; break; } } if (enemyType == null) { Debug.LogError("Item type didn't get chosen for some reason."); } // We should now have figured out which enemy type to spawn, so spawn one! GameObject enemyGO = Instantiate(enemyPrefab); // Get the enemy component. Enemy enemy = enemyGO.GetComponent <Enemy> (); // Now setup all of its values. /// ENEMY SETUP - Add more things? e.g. name / armour. enemy.maxHealth = enemy.health = enemyType.health; enemy.attack = enemyType.attack; enemy.range = enemyType.range; enemy.x = x; enemy.y = y; enemy.transform.position = new Vector3(enemy.x, enemy.y, -1); // Get the sprite renderer, and set the enemy's sprite. enemy.GetComponent <SpriteRenderer> ().sprite = enemyType.GetSprite(); // Should be done. }