- Home /
Trying to avoid repeating elements on list (random.range)
This is a bit of a followup to this post: https://answers.unity.com/questions/1709250/transformrotate-on-z-axis-moves-the-entire-object.html?childToView=1709334#comment-1709334
I have a circle of 4 colors, and the player gets one of these colors randomly when it collides with a certain object.
What I'm trying to do is to make sure that the player doesn't pick the same color twice in a row. I tried clearing the list of colors and then resetting it by adding a copy of the original list to the list, like so:
public class Player : MonoBehaviour
{
public float jumpForce = 10f;
public string currentColor;
public List<Color> colors;
public List<Color> copy;
Rigidbody2D rb;
SpriteRenderer sr;
void Start()
{
rb = GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
SetRandomColor();
}
void Update()
{
if(Input.GetButtonDown("Jump") || Input.GetMouseButtonDown(0))
{
rb.velocity = Vector2.up * jumpForce;
}
}
private void OnTriggerEnter2D(Collider2D col)
{
if(col.tag == "ColorChanger")
{
SetRandomColor();
Destroy(col.gameObject);
return;
}
if(col.tag != currentColor || col.tag == "Border")
{
Debug.Log("GAME OVER!");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
void SetRandomColor()
{
int index = Random.Range(0, colors.Count);
switch(index)
{
case 0:
currentColor = "Cyan";
sr.color = colors[0];
colors.RemoveAt(0);
break;
case 1:
currentColor = "Yellow";
sr.color = colors[1];
colors.RemoveAt(1);
break;
case 2:
currentColor = "Purple";
sr.color = colors[2];
colors.RemoveAt(2);
break;
case 3:
currentColor = "Pink";
sr.color = colors[3];
colors.RemoveAt(3);
break;
}
ResetColorList();
}
void ResetColorList()
{
if(!colors.Any<Color>())
{
Debug.Log("List is empty");
colors.AddRange(copy);
}
}
}
This is what the player looks like:
The player does change color, and everything else in the code works , but I don't know how to avoid the repeating numbers in the list. Any help would be appreciated.
Answer by martygrof3708 · Mar 20, 2020 at 12:33 AM
You could use a third temporary list to randomize the colors, like so:
List<Color> temp = colors;
while ( temp.Count > 0 )
{
int randomNumber = UnityEngine.Random.Range( 0 , temp.Count );
copy.Add( temp[ randomNumber ] );
temp.RemoveAt( randomNumber );
}
This way there is a very small chance you could still get the same exact order.
Do I use this methid once after the switch statement, or in every single case?