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!

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.