Displaying random names without them repeating

Twine Version: 2.3.14
Story Format: 2.34.1

So i’m trying to display the “names” of 3 out of 5 objects that are in an array($AvailabeUnits).
Object example:

<<set $Unit1 = {
“name” : “Jennifer”,
“skill1”: “Healing”,
“skill2”: “Staff”,

I use this code to get the random names:

<<set $RandomGeneratorNumber = $AvailableUnits.length -1>>
<<set $Unit1 = random($RandomGeneratorNumber)>>
<<set $Unit2 = random($RandomGeneratorNumber)>>
<<set $Unit3 = random($RandomGeneratorNumber)>>

<<print $AvailableUnits[$Unit1].name>>
<<print $AvailableUnits[$Unit2].name>>
<<print $AvailableUnits[$Unit3].name>>

and that works fine except they can repeat themselfs. i want every name to only appear once if at all. i tried to pluck them out of the array and reset the variable ($RandomGeneratorNumber) but that doesn’t work becuase i’m trying to print the names after i plucked them (preferably in a new passage). i could print them before i pluck them but then if i add an option to look at the unit which takes them to another passage and they come back, depending on how i set it up, everything either rerolls the choices or it just can’t find most of the objects names.

Additonal Info that might be relevant:
The array ($AvailableUnits) size will change all the time during playing.
It’s always going to display 3 names out of the array no matter how big it is (It won’t get smaller than 3)
at the end when the player choses one name i need to pluck that one from the array which is why i’m using the three variables $Unit1 $Unit2 $Unit3

In Short:
Displaying 3 Random names out of an array wihtout repeating them or having the chance of rerolling them accidently.

You should be able to use Array.pluck() or pluckMany().

<<set $Unit1 = $AvailableUnits.pluck()>>

Then you can <<print $Unit1.name>> directly instead of going through $AvailableUnits.

Or you could use pluckMany to grab three at once:

<<set $Units to $AvailableUnits.pluckMany(3)>>
<<print $Units[0].name>>
<<print $Units[1].name>>
<<print $uUnits[2].name>>

Also, you’ll want to use the “Preformatted Text” </> button on your code: you got lucky this time and the forum didn’t eat anything important, but it often does.

1 Like

That’s so much less code than i expected. Thank you very much it works perfectly. I can then probably just use “push” to add the the 2 that didn’t get selected back into the array. Also thanks i see the button now and will use it in the future.

1 Like