Attempt to index nil with parent

hello, i got once again bored and decided to make a ambush where it picks random police officers to attack you, but uh something doesnt let it slide


and heres the code
(edit: i put the full code)

local batons = script.BatonMains
local batonschildren = batons:GetChildren()
batons.Parent = nil
wait(0.1)

local police = batonschildren[math.random(1,3)]:Clone()
police.Parent = script.Parent.spawned
police.Name = "POLICE"
script["1x1x1x1"]:Play()
local plrs = game.Players:GetPlayers()
for i = 1,#plrs do
	local gui = script["GTA REAL"]:Clone()
	gui.Parent = plrs[i].PlayerGui
	gui.CHANGE.Disabled = false
end```
1 Like

To put text in code form, do this:

```Lua
print(‘Hello world!’)
```
Output:

print('Hello world!')

But as far as your script goes, a clone’s parent will automatically be nil. It seems that script.Parent is nil on the line of:

police.Parent = script.Parent.spawned
1 Like

i put the full code now. wonder if its because the folder is in nil

1 Like

May I ask why you added this spawned to the end of police.Parent = script.Parent?

1 Like

well its the model where the cops spawn so they dont spawn in workspace and dont despawn
em

script.Parent.Spawned

If this is the line that has the error, it looks like Spawned is a child of the script, and not the script’s parent. Also you should use a folder instead of a model instance.

Oh and not that it matters, but you should use task.wait() instead of wait(), as it’s deprecated.

1 Like

When you set something to nil all its children/descendants also become nil so the parent would no longer be the older but nil

Use a Folder and name it spawned instead of a Model.

1 Like

Try remove batons.Parent = nil and see if it fixes it

em

Tbh thats really sus (char limit)

1 Like

Make sure you use WaitForChild or yield until every baton has loaded. It’s most likely trying to reference a baton that doesn’t exist at the moment the line is being executed.

local batons = script.BatonMains
while #batons:GetGetChildren() < 3 do task.wait() end -- yield until 3 batons have loaded
local batonschildren = batons:GetChildren()
batons.Parent = nil

local police = batonschildren[math.random(1,3)]:Clone()
police.Parent = script.Parent.spawned
police.Name = "POLICE"
script["1x1x1x1"]:Play()
local plrs = game.Players:GetPlayers()
for i = 1,#plrs do
	local gui = script["GTA REAL"]:Clone()
	gui.Parent = plrs[i].PlayerGui
	gui.CHANGE.Disabled = false
end