In various scenarios using things such as ChildAdded or DescendantAdded, and then immediately modifying the Parent property of the instance, or even destroying the instance, I have come across this error:
“Something unexpectedly tried to set the parent of instance to NULL”
What is the absolute best way to circumvent this error that would work in any scenario where I would need to immediately change the Parent of an instance after being changed beforehand?
For example, if I needed to immediately destroy any instance added into a specific object, I would do something like this:
Without adding any sort of delay, the object would be destroyed on the same frame as it was added, which, from my understanding, is what results in that error.
Using task.defer() on the :Destroy() call would consistently give it enough time (until the *next resumption cycle), to avoid that error from occurring.
I wouldn’t recommend this way of calling :Destroy(). It’s slower than just:
task.defer(function()
child:Destroy()
end)
I benchmarked both of them using this code:
local function benchmark1()
local a = Instance.new("Part")
local b = os.clock()
a.Destroy(a)
return os.clock() - b
end
local function benchmark2()
local a = Instance.new("Part")
local b = os.clock()
a:Destroy()
return os.clock() - b
end
for g = 1, 100 do
local avg1 = {}
local avg2 = {}
local sum1 = 0
local sum2 = 0
for i = 1, 100 do
table.insert(avg1, benchmark1())
table.insert(avg2, benchmark2())
end
for _, avg in avg1 do sum1 = sum1 + avg end
for _, avg in avg2 do sum2 = sum2 + avg end
sum1 /= #avg1
sum2 /= #avg2
print(sum1 > sum2)
end
And here are the results:
It may be a fancier way of doing it, and being faster to write, but I always use the latter, it’s faster.
Yea I use the AI to mostly help or editing something but it works mostly with all the things I tested with such as turning a model into rainbow on touch even with meshes