New to unity and I am unsure of what makes sense here for best practice. I have a spawner that periodically creates new powerups the type of power up (bomb, blaster..ect) created is random. Here are the two ways that seem to work for creating this behavior:
Spawner.cs
public void spawnPowerUp()
{
// Add a powerup to the game hierarchy
GameObject powerUpObject = Instantiate(powerUp, randomSpotOnPlayfield(), transform.rotation);
// Assign a random powerup to this instance
powerUpObject.GetComponent<PowerUp>().powerUpType = (PowerUpTypes)UnityEngine.Random.Range(0, Enum.GetValues(typeof(PowerUpTypes)).Length);
}
The issue with this is that my spawner shouldn’t really care what type of power up it created. I want separation of concerns. The logic of selecting a random powerup feels like it should be handled within the powerUp class. The only way I can think to do that is writing code like this:
PowerUp.cs
public class PowerUp : MonoBehaviour
{
public PowerUpTypes powerUpType;
void Start()
{
RandomizePowerUpType();
}
public void RandomizePowerUpType()
{
powerUpType = (PowerUpTypes)UnityEngine.Random.Range(0, Enum.GetValues(typeof(PowerUpTypes)).Length);
}
}
PowerUpTypes.cs
public enum PowerUpTypes
{
Bomb, Blaster
}