C# Having troubles with creating/referencing a random list.
Basic Rundown is, I'm creating a random X and Y position based around an 2D image array to create the possible choices in game for the player. But i want to check the list as it is being made, to make sure that the new possibility is NOT in the list, to avoid Repeat options.
Here is what i have.
using System;
int[] listX; new int[5]
int[] listY = new int[5];
int[] ranXY = new string[5];
for (int i=0; i<5;i++){
int ranX = Random.Range(0,3); //Makes random X,Y coords
int ranY = Random.Range(0,2);
ranXY[i] = ""+ ranX+ ranY; // Combines the 2 into a string for later verification
int ranXY= Array.IndexOf(ranXY, ranXY[i]); // IndexOf to find if new XY exists in list
if (ranXY !=0 |... | ranXY!=4) // checks if the new item is in the list already
{ //If successful, Add new XY to list of possibilities.
listX[i] = ranX;
listY[i] = ranY;
}
else{ i-=1;}
}
Based on what i have here, it should create a set of random numbers in 2 lists, save each list to a string combined, check the list of combined XY coords, for the current random selection, and if it doesn't find the combo, adds it to the current position. If it does find the combo, repeat the process for the same array position until it finds a new combination.
The issue i am having, is i still end up with Repeat items in my list.
If i change if (ranXY!=0) etc. to if (ranXY= -0) it freezes unity on pressing play. I can't seem to find where the feedback loop is happening or what. After checking documentation for the functions i am using, everything should be tip-top.
please keep in mind, i have only been working with unity and C# for roughly 2 weeks, and have limited coding background before this. But i am a fast learner, and would Greatly appreciate any help fine tuning this code.
Lastly, had some issues formatting this post properly, not sure if the new line function works proper etc... so apologies for the kind of mess this is.
Answer by CheezyTatoSoup · Feb 09, 2021 at 08:25 PM
I figured it out... I was checking the list AFTER i put the item in, so OF COURSE it will find the item in the list... so it was going "Yes, it is there, repeat. Yes it is there, repeat" etc etc etc.....
I simply added a string 'check' in place of the "current combined Coords" variable. now it works, with no repeats.
wow... but YAY i got it. Thanks Unity Forums!
Your answer
Follow this Question
Related Questions
String to int conversion not working in ControllerCollider method although I am sure it is an int... 1 Answer
How do you spawn a gameobject based on last object in array and limit that within a range? 1 Answer
Trying to spawn enemies on only one path 1 Answer
Error FormatException: Input string was not in a correct format. 0 Answers
Random.Range returns either 1 or 2 2 Answers