Math.random() Returning 1

I might be making a stupid mistake or be completely blind because this usually works. But I’m using math.random to choose a random model from a folder, and then clone it, and then change the player’s character to it. Basically, morph the player, it keeps returning 1 though, this is my code:

local randomObject = Models[math.random(1, #Models:GetChildren())]
local oldModel = player.Character
local newModel = randomObject:Clone()
local oldCFrame = oldModel:GetPrimaryPartCFrame()
newModel.Name = player.Name
player.Character = newModel
newModel.Parent = workspace
newModel:SetPrimaryPartCFrame(oldCFrame)
oldModel:Destroy()
Status.Value = player.Name.." became a "..randomObject.Name

Is it because there is only 1 model in the Models folder?

Currently, there’s only 1 model in the folder, yes.
I just tested it with two and now it either returns 1 or 2, still not an instance.

That is why math.random is only returning 1. You are asking for a random number between 1 and 1, therefor returning 1.

What I meant was I want it to return the instance, not an integer.

Is Models a table type or Instance type?

Models is a folder.

You will need to change this line:

to I believe:

local randomObject = Models:GetChildren()[math.random(1, #Models:GetChildren())]
2 Likes

Ah, yes. That’ll be it. Stupid mistake then. :sweat_smile:

1 Like

You need to use :GetChildren to index a random object because Models is an instance.

local randomObject = Models:GetChildren()[math.random(1, #Models:GetChildren())]
1 Like