How do I not break an OOP function when self is destroyed?

To give an example of the issue, lets say we have a reload function for a OOP weapon. If I unequip the weapon, I should destroy it to save memory and resources. However, If I execute the reload function, it’ll break because its not gonna know what values its referencing anymore.

function module:Reload()
	self.Reloading = true

	task.wait(self.ReloadTime)

	--It's gonna break here because the weapon will be unequipped already and not know what its   referencing.

	self.CurrentAmmo = self.AmmoPerMag
end)

Another example would be a callback function for a projectile module. So if I fire the weapon and I give a callback function for when the projectile impacts something it’ll break.

function module:Shoot()
	self.FireSound:Play()
	
	--Cast projectile
	
	ProjectileHandler:castProjectile({
		origin = self.FirePoint.WorldPosition,
		Speed = self.ProjectileSpeed,
		CallbackFunction = function(castResult)
			local hum = castResult.Parent:FindFirstChild("Humanoid")

			if hum then
				hum:TakeDamage(self.ProjectileDamage) --Would error here
			else
				createProjectileImpactEffect(castResult.Position, self.ProjectileImpactType) --Would error here aswell
			end
		end,
	})
end
})

A possible fix could be to make a bunch of local variables every time the function is executed, but that’s like a band aid and would not be efficient. If anyone knows a better solution please let me know, thank you!

1 Like

Probably just don’t destroy it until it’s not gonna be used again

If you can, temporarily destroy or disable anything / disconnect whatever you don’t need. But I wouldn’t destroy self until the weapon is destroyed or you completely don’t need the class anymore.

i mean, shouldnt it break? isnt that the whole idea of oop

local part = Instance.new("Part", workspace)

task.spawn(function()
	task.wait(5)
	part:Destroy()
	part = nil
end)

while task.wait() do
	print(part:GetTouchingParts()) --> would error after 5 seconds, as expected
end

if you destroy a class and try to use a method of said destroyed class, it should error

Like many others are saying don’t destroy the class until it’s not needed anymore. It shouldn’t really be too bad keeping it unless you have a ton of properties and would probably be more resources efficient to just save the class rather than recreating it each time. However if you run into similar issues, use pcall wnd do checks. Find places where it’s possible for the code to error (such as referencing a possible nil value after a yield) and make sure that everything is possible before continuing. In this case make sure self isn’t nil

If the player dies then should it be destroyed? (for a weapon)

Yes, I’d assume they’re not going to use the same weapon again after they die

1 Like