- Home /
Question by
AsclepiiusUnknown · Jun 25, 2020 at 10:40 AM ·
c#unity 2dwords
How to cycle through random letters and make a word
The below code is what I've come up with so far to do what I want. Basically I want to have a string (in this case SEAMLESS) and for each letter in this string I want to cycle through random letters until they are the same. When they are the same I want to save them in the array of letters and then at the end form the word. The goal is to get an effect similar to this but with letters instead of numbers.
public string word = "SEAMLESS";
private string builtWord;
public char[] letters;
public Text displayBox;
string uppercaseAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private void Start()
{
letters = word.ToCharArray();
}
private void Update()
{
for (int i = 0; i < letters.Length; i++)
{
char randomLetter = UppercaseLetter();
while (randomLetter != letters[i])
{
letters[i] = randomLetter;
print("letter: " + letters);
print("random letter: " + randomLetter);
if (randomLetter == letters[i])
{
builtWord = builtWord + letters[i];
print("built word: " + builtWord);
return;
}
randomLetter = UppercaseLetter();
return;
}
if (randomLetter == letters[i])
{
}
}
}
public char UppercaseLetter()
{
char letter = uppercaseAlphabet[Random.Range(0, uppercaseAlphabet.Length)];
//letter = (char)('A' + Random.Range(0, 26)); //Alternative way of getting letter using ASCII
return letter;
}
Comment
Best Answer
Answer by Hellium · Jun 25, 2020 at 01:27 PM
public string word = "SEAMLESS";
public Text displayBox;
private void Start()
{
BuildWorld(1.5f, 2, 0.08f, 0.12f);
}
private void BuildWorld(float minTime, float maxTime, float minTimeStep, float maxTimeStep)
{
char[] letters = word.ToCharArray();
for (int i = 0 ; i < letters.Length ; i++)
{
int index = i;
char finalLetter = letters[index];
System.Action onTick = () => ChangeLetterToRandom(letters, index);
System.Action onComplete = () => ChangeLetter(letters, index, finalLetter);
float timeStep = Random.Range(minTimeStep, maxTimeStep);
StartCoroutine(RunTimer(onTick, onComplete, Random.Range(minTime, maxTime), timeStep));
onTick();
}
}
private IEnumerator RunTimer(System.Action onTick, System.Action onComplete, float maxTime, float timeStep)
{
for(float t = 0 ; t < maxTime ; t += Time.deltaTime)
{
while(t > timeStep)
{
timeStep += timeStep;
onTick();
}
yield return null;
}
onComplete();
}
private void ChangeLetterToRandom(char[] letters, int index)
{
char letter = (char)('A' + Random.Range(0, 26));
ChangeLetter(letters, index, letter);
}
private void ChangeLetter(char[] letters, int index, char letter)
{
letters[index] = letter;
displayBox.text = new string(letters);
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
DIsabling a Box Collider Trigger after cut scene 2 Answers
Collider Array showing up empty,No Colliders showing up in my array 0 Answers
Save randomly placed objects 0 Answers