This one was tricky, I had to refactor my code but I think I found a good solution (I don’t know if it was a better way to do it)
The whole “magic” it’s made in the ColorChanger.cs
ColorChanger.cs code:
public class ColorChanger : MonoBehaviour
{
public enum ColorOptions
{
Red = 1,
Yellow = 2,
Blue = 3
}
private SpriteRenderer mySpriteRenderer;
[SerializeField] private ColorOptions myColor;
void Awake()
{
mySpriteRenderer = GetComponent<SpriteRenderer>();
}
private void Start()
{
if (this.CompareTag("Block"))
{
ChangeColor(GetRandomEnumNumber());
}
else
{
ChangeColor((int)myColor);
}
}
private int GetRandomEnumNumber()
{
int randomNumber = Random.Range(1, System.Enum.GetValues(typeof(ColorOptions)).Length + 1);
return randomNumber;
}
public void ChangeColor(int colorNumber)
{
switch (colorNumber)
{
case (int)ColorOptions.Red:
mySpriteRenderer.color = Color.red; break;
case (int)ColorOptions.Yellow:
mySpriteRenderer.color = Color.yellow; break;
case (int)ColorOptions.Blue:
mySpriteRenderer.color = Color.blue; break;
}
}
}
SpawnNewBlock.cs code:
public class SpawnNewBlock : MonoBehaviour
{
[SerializeField] GameObject blockPrefab;
[SerializeField] Transform spawnPosition;
private Vector2 spawnOffset;
public void SpawnBlock()
{
float randomNumber = Random.Range(0, 6f);
spawnOffset = new Vector2(randomNumber, 0f);
GameObject newBlock = Instantiate(blockPrefab, (Vector2)spawnPosition.position + spawnOffset, Quaternion.identity);
}
}