Spawning Random Colored Block

I could not get the random color spawning working in the SpawnNewBlock.cs, for the life of me. So i opted for this method in the ColorChanger.cs Script instead.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColorChanger : MonoBehaviour
{
    public SpriteRenderer mySpriteRenderer;

    public Color colors;
    public enum ColorPic { Red, Yellow, Blue, Random};
    [SerializeField] public ColorPic color;

    public int randomColor;

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

    private void Start()
    {
        ColorSwitch();
    }

    public void OnTriggerEnter2D(Collider2D collison)
    {
        if(collison.gameObject.CompareTag("Gem"))
        {
            mySpriteRenderer.color = collison.gameObject.GetComponent<SpriteRenderer>().color;
        }
    }

    public void ColorSwitch()
    {
        switch (color)
        {
            case ColorPic.Red:
                colors = Color.red;
                break;
            case ColorPic.Blue:
                colors = Color.blue;
                break;
            case ColorPic.Yellow:
                colors = Color.yellow;
                break;
            case ColorPic.Random:
                RandomColorPic();
                break;
        }

        mySpriteRenderer.color = colors;
    }

    public void RandomColorPic()
    {
        randomColor = Random.Range(0, 3);

        if (randomColor == 0)
        {
            colors = Color.red;
        }
        else if (randomColor == 1)
        {
            colors = Color.blue;
        }
        else if (randomColor == 2)
        {
            colors = Color.yellow;
        }
    }
}

Just to note that on the Prefab within Unity I set the Color To Random as every time one spawns it should be random. and if the developer places a block they have to the choice to choose what color they wish from the dropdown menu

3 Likes

I know this is way late, but keep it clean and putting another example…this is in SpawnNewBlock.cs:

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

    public void SpawnBlock()
    {
        GameObject spawnedBlock = Instantiate(blockPrefab, spawnPosition.position, Quaternion.identity) as GameObject;
        switch (Random.Range(0, 3))
        {
            case 0:
                spawnedBlock.GetComponent<SpriteRenderer>().color = Color.red;
                break;
            case 1:
                spawnedBlock.GetComponent<SpriteRenderer>().color = Color.yellow;
                break;
            case 2:
                spawnedBlock.GetComponent<SpriteRenderer>().color = Color.blue;
                break;
        }
    }
}```

Privacy & Terms