unity-game-enginerandomunityscript

How to randomize data in unity using JavaScript


I have a text file in project with some text data. Using below code I'm showing my data one line at a time when player click on a button (called NEXT).

For some reason what I want to do is make a button called "RANDOM". And when player will click on that a random line from the text file will be shown.

Here is my UnityScript Code:

#pragma strict
  
import UnityEngine;
import UnityEngine.UI;
  
var textFile : TextAsset;
var dialogLines : String [];
var lineNumber : int;
  
var uiText : Text;
var canvas : Canvas;
  
  
function Start () {
    if (textFile){
        dialogLines = (textFile.text.Split("\n"[0]));
    }  
}
  
function Update () {
    if (lineNumber <0){
        lineNumber = 0;
    }
  
    var dialog : String = dialogLines[lineNumber];
    uiText.text = dialog;
}
  
function Next () {
    var randomLine = Math.floor((Math.random() * dialogLines.length) + 1); //1-10
    //if dialogLines is not strictly typed, go ahead and use dialogLines.length instead of 10
    return dialogLines[randomLine];
}

Solution

  • You can use a function like so

    function randomLine() {
      var randomLine = Math.floor((Math.random() * 10) + 1); //1-10
      //if dialogLines is not strictly typed, go ahead and use dialogLines.length instead of 10
      return dialogLines[randomLine];
    }