Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I make a random music play?

Asked by 4 years ago

I'm trying to make a random ambience selector for a game I am making. I kind of understand the basic idea of a random music selector, but I don't at the same time, if that makes sense. This is my script, am I getting the right idea at all? (the script isn't finished it's just a concept)

local ambiences = {script.Ambience1, script.Ambience2}

for a = 1, #ambiences do

end

1 answer

Log in to vote
1
Answered by
Fifkee 2017 Community Moderator Moderation Voter
4 years ago
Edited 4 years ago

When making a piece of code that gives you a random value, you'll need to know of two things:

The "length" operator of the table: #, and table keys, signified by square brackets.

Table keys take in an identifier that the table has. It's typically used to capture elements via variable, or to capture elements with spaces. For example, if you wanted to capture an object in a dictionary, but the index has a space, this wouldn't work: table.table index, instead, you'd have to use table["table index"]. This can also be used to get a child that has a space in their name, like this: print(workspace["Custom Object"].PrimaryPart);.

The length operator can be placed behind two things: A string #("Hello, world!") and a table. #({1,2,3,4,5}), the two examples should return 13 and 5 respectively. And please note that the length operator only works on arrays, not dictionaries.

You can utilize the math.random with a base of 1 (where Lua tables start) up to the length of the table (#tableName) to get a piece of code that looks like this: math.random(1, #tableName), #tableName being the amount of objects inside of the table.

In an array, all indices are numbers, so you can index an array value by using a number, lets say 2: ambiences[2], which will return script.Ambience2. Since math.random(1, #tableName) will always return an integer that is used as a table index, we can use that in a key, like so:

tableName[math.random(1, #tableName)].

Make sure that your parenthesis and brackets are lined up. For one bracket, there should be another.

Substituting variable names for yours, you should get ambiences[math.random(1, #ambiences)]

An elongated form (using variables) looks like this, replacing the math.random key with a variable.

local ambienceValues = {script.Ambience1, script.Ambience2};

function getRandomAmbience()
    local randomValue = math.random(1, #ambienceValues);
    return ambienceValues[randomValue];
end

getRandomAmbience();

If this helped, go ahead and drop an upvote, and mark as the answer. Thanks!

Ad

Answer this question