Connecting RunService:Heartbeat to a class method

I’m using dash to implement oop in my project and I’m having trouble connecting a method to heartbeat.

Here’s the code for the class:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")

local class = require(ReplicatedStorage.Packages.dash)["class"]


local Sword = class("Sword", function(character: Model) return
    {
        character = character,
        sword = Instance.new("Part")
    }
end)

function Sword:_init()
    local rootPart = self.character:WaitForChild("HumanoidRootPart")
    self.sword.CFrame = CFrame.new(rootPart.Position + Vector3.new(0, 3, 0))
    self.sword.Parent = game.Workspace

    self:_update(5)
    RunService.Heartbeat:Connect(self._update)
end

function Sword:_update(step)
    local rootPart = self.character.HumanoidRootPart
    self.sword.CFrame = CFrame.new(rootPart.Position + Vector3.new(0, 3, 0))
end


return Sword

The update method works properly when called with self:_update(5), however with heartbeat an error occurs:
Players.F1ndlay.PlayerScripts.Client.Sword:24: attempt to index number with ‘character’
when the method is called by heartbeat, self is a number rather than a Sword object. (seems similar to if you were to call self:_update(5))

I’ve been stuck on how to solve this, so any feedback would be great.

Try this, since right now you are using self._update instead of self:_update so you’ll need to pass self through.

RunService.Heartbeat:Connect(self._update, self)

I’m still getting the same issue. step is nil if it helps. Do I need to change the update method to work with the change?

Just connect the function this way instead.

RunService.Heartbeat:Connect(function(dt)
   self:_update(dt)
end)
1 Like

Oh maybe try this, this should work. Edit: Pretty much what @0_1195 did

RunService.Heartbeat:Connect(function(step)
    self:_update(step)
end)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.