CLONING COLORS QUEST: " Spawn A Random Colored Block " - Solutions

This is my solution
I communicate between SpawnNewBlock.CS and ColorChanger.CS so I can choose a random color from Enum. ( I’m using “_CurrenColer = (Colors)randomValue;” so i can get the color from enum using values) :grin:

[SpawnNewBlock.Cs]

using UnityEngine;

public class SpawnNewBlock : MonoBehaviour
{
    [SerializeField] GameObject blockPrefab;
    [SerializeField] Transform spawnPosition;
    private GameObject[] currentBlock = new GameObject[100000];
    private int blockIndex = 0;
    



    public void SpawnBlock()
    {
        currentBlock[blockIndex] =  Instantiate(blockPrefab, spawnPosition.position, Quaternion.identity);
        currentBlock[blockIndex].GetComponent<ColorChanger>().RandomColors();
        blockIndex++;
    }

[ColorChanger.CS]

using UnityEngine;

public class ColorChanger : MonoBehaviour
{
    private SpriteRenderer mySpriteRenderer;
    private Color myColor;

    void Awake()
    {
        mySpriteRenderer = GetComponent<SpriteRenderer>();
    }

    private enum Colors
    {
        Yellow = 1,
        Cyan = 2,
        Red = 3 
    }

    [SerializeField]
    private Colors _CurrenColer;

    private void Start()
    {
        switch (_CurrenColer)
        {
            case Colors.Yellow:
                myColor = Color.yellow;
                break;
            case Colors.Cyan:
                myColor = Color.cyan;
                break;
            case Colors.Red:
                myColor = Color.red;
                break;
        }

        mySpriteRenderer.color = myColor;
    }

       public void RandomColors()
    {
        // Random Enum Value
        int randomValue = Random.Range(1, 4);
        // Random Colors
        _CurrenColer = (Colors)randomValue;
    }
}
2 Likes

My solution was a bit more static, though I like the idea of using the Enum I created in ColorChanger and may go back and work it some more.

[SpawnNewBlock.cs]

public class SpawnNewBlock : MonoBehaviour
{
    [SerializeField] GameObject blockPrefab;
    [SerializeField] Transform spawnPosition;
    Color myColor;

    public void SpawnBlock()
    {
        switch (Random.Range(0, 3))
        {
            case 0:
                myColor = Color.red;
                break;
            case 1:
                myColor = Color.blue;
                break;
            case 2:
                myColor = Color.yellow;
                break;
        }

        GameObject myGameObject = Instantiate(blockPrefab, spawnPosition.position, Quaternion.identity) as GameObject;
        myGameObject.GetComponent<SpriteRenderer>().color = myColor;
    }
}
1 Like