1

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]; } 

2 Answers 2

0

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]; } 
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks guys. I will let you know the result soon :)
It is saying [Unknown identifier: "Math"]
nice, is everything working as intended or do you have any additional questions?
[ERROR] It is saying [Unknown identifier: "Math"]
That's bizarre, Math is just like a default library. I just checked unityscript stuff and found you have to use this docs.unity3d.com/ScriptReference/Random.html instead of Math.random, that's kinda dumb but whatever
|
0

Since you have your file split into an array just do grab a random line number.

Math.rndRange = function ( min, max ){ if( isNaN(min) || isNaN(max) ) return NaN; return Math.round(Math.random()*(max-min)+min); } 

Maybe do a floor or something instead of round. W.e you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.