Random.Range(min, max) returns values inferior to min,Random.Range() returns values inferior to min

I just began learning unity and c# and I am currently trying to recreate the mobile game Color Switch. I am using Random.Range() to randomly change the color of my player when he hits a switcher, But the function sometimes returns 0 as a value (minimum being 1), making me stuck on one color forever.

Here’s my script:

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

public class BallSwitch : MonoBehaviour
{
    int Number;
    int Color;
    public Sprite Blue;
    public Sprite Yellow;
    public Sprite Purple;
    public Sprite Pink;
    public SpriteRenderer Ball;
    // Start is called before the first frame update
    void Start()
    {
        Color = Random.Range(1, 5);
    }

    // Update is called once per frame
    void Update()
    {
        if(Color == 1)
        {
            Ball.sprite = Blue;
            gameObject.tag = "Blue";
        }
        else if(Color == 2)
        {
            Ball.sprite = Yellow;
            gameObject.tag = "Yellow";
        }
        else if(Color == 3)
        {
            Ball.sprite = Purple;
            gameObject.tag = "Purple";
        }
        else 
        {
            Ball.sprite = Pink;
            gameObject.tag = "Pink";
        }
        Debug.Log(Color.ToString());
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.CompareTag("Switcher"))
        {
            if (Number == Color)
            {
                Number = Random.Range(1, 5);
            }
            else
            {
                Color = Number;
            }
            collision.GetComponent<CircleCollider2D>().enabled = false;
            collision.GetComponent<SpriteRenderer>().enabled = false;
        }
    }
}

,

You’re not setting Number in OnTriggerEnter before testing it in the if() statement. It’s private, so I assume you’re not setting it anywhere else.

It will by default initialise as 0. So you’re immediately jumping to the else, assigning Color to 0, and the Random.Range never runs.

I think the behaviour you possibly want would just need 1 line of code (+2 to disable stuff) in OnTriggerEnter:

 if(collision.gameObject.CompareTag("Switcher"))
         {
             Color = Random.Range(1, 5);
             collision.GetComponent<CircleCollider2D>().enabled = false;
             collision.GetComponent<SpriteRenderer>().enabled = false;
         }