Random color is not unique

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By TheColorRed

I am trying to randomly modulate a color on a sprite when the sprite is created. However, when all the sprites are created they are always the same color. What is causing this?

In my main scene, I Instantiate a child scene which has the below script attached to the sprite in that scene. I then duplicate it a few times and run the game and all items are the same color.

using Godot;
using System;

public enum Gender { Male, Female }

public class Rat : Sprite {

    [Export] public Gender gender { 
      get { return _gender; } 
      protected set { _gender = value; } 
    }

    private Gender _gender;

    public override void _Ready() {
        InitGender();
    }

    private void InitGender() {
        var num = new Random().Next(0, 2);
        // Select gender
        gender = num == 0 ? Gender.Male : Gender.Female;

        // Set gender's color
        SelfModulate = new Color(gender == Gender.Male ? "6555ed" : "d425b9");
    }
}
:bust_in_silhouette: Reply From: TheColorRed

The issue has to do with the usage of Random [Source]:

If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

So, what I did was create a static field called rand and just used rand.Next(0, 2) where I would like to get a random number.

using Godot;
using System;

public enum Gender { Male, Female }

public class Rat : Sprite {

    private static Random rand = new Random();

    [Export] public Gender gender { 
      get { return _gender; } 
      protected set { _gender = value; } 
    }

    private Gender _gender;

    public override void _Ready() {
        InitGender();
    }

    private void InitGender() {
        // Select gender
        gender = rand.Next(0, 2) == 0 ? Gender.Male : Gender.Female;

        // Set gender's color
        SelfModulate = new Color(gender == Gender.Male ? "6555ed" : "d425b9");
    }
}