Replace one random char in a string
Hi there,
I'm currently working on a script for changing a random char in a string. Here's what I've got so far:
import System.Text;
#pragma strict
var speed : float = 0.5;
var text : UI.Text;
var chars : int = 1500;
var oldText : StringBuilder;
function Start () {
oldText = new System.Text.StringBuilder(text.text);
Change();
}
function Change () {
while(true) {
oldText[Random.Range(0, chars-1)] = Random.Range(0, 2);
text.text = oldText.ToString();
yield WaitForSeconds(speed);
}
}
When I hit play, the text just vanishes in steps. I don't know, what I'm doing wrong.
Thanks for your response!
I figured it out. If anyone is interested in the code, here you go:
import System.Text;
#pragma strict
var speed : float = 0.5;
var text : UI.Text;
var chars : int;
var oldText : StringBuilder;
function Start () {
oldText = new System.Text.StringBuilder(text.text);
chars = oldText.Length;
Change();
}
function Change () {
var numChars = ['0', '1'];
while(true) {
var random = Random.Range(0, chars-1);
oldText.Chars[random] = numChars[Random.Range(0, 2)][0];
text.text = oldText.ToString();
yield WaitForSeconds(speed);
}
}
Thanks to Ahndrakhul for the help!
Answer by Ahndrakhul · May 21, 2016 at 10:36 PM
Are you attempting to replace characters in the stringbuilder with random 1's and 0's? I think that in C# you would get an error trying to do this, but maybe javascript automatically casts ints to chars. What's probably happening is that your characters are being replaced by whatever characters correspond to 0 and 1 in ascii or unicode code. I think 0 is null.
could you try using the random number to pick a character out of an array?
function Change ()
{
var numChars = ['0', '1'];
while(true)
{
oldText[Random.Range(0, chars-1)] = numChars[Random.Range(0, 2)];
text.text = oldText.ToString();
yield WaitForSeconds(speed);
}
}
Sorry if the array isn't declared correctly. I really don't know javascript well at all.