Question about OOP!

Did you change the module script at all? That should work fine. If you define both as a method or both as a constructor, it doesn’t really matter which; it’s just a styling issue.

2 Likes

Answering to both, I changed to . and it doesn’t works, tried with : and doesn’t works the module:

local module = {}

module.__index = module

function module:NewPlayer(ok)
	local PlayerData = {
		player = ok
		
	}
	local MetaTable = setmetatable(PlayerData, module)
	

	return PlayerData
end

function module:AddHealth(health)
	self.player.Character.Humanoid.Health = self.player.Character.Humanoid.Health - health
end

return module

Are you sure I can pass the player to the newplayer function?

Oh, you’re calling mod:AddHealth in the main script. Try calling player:AddHealth instead.

2 Likes

Never mind I see the issue.

mod:AddHealth(100)

You are calling the method on the “base” where all the methods are stored, and not on a speciifc instance.

This is how most OOPs are structured

local Pizza = { } -- just an example
Pizza.__index = Pizza

function Pizza.create(flavor, slice_count)
    return setmetatable({ Flavor = flavor, Slices = slice_count }, Pizza)
end

function Pizza:Eat()
    self.Slices = self.Slices - 1
end

local new_pizza = Pizza.create("Pepperoni", 8)
new_pizza:Eat()
print(new_pizza.Slices) -- 7

You call the method on an instance of the class.

1 Like

Oh lol, yes, you’re right, it’s not working bc of you know tipically, you need to add :waitforchild() attempt to index field ‘Character’ (a nil value) Because it breaks 00:40:53.481 - Infinite yield possible on ‘Players.ignacasas06:WaitForChild(“Character”)’

yeah, add this:

game.Players.PlayerAdded:Connect(function(p)
        local char = p.Character or p.CharacterAdded:Wait()
	local player = mod:NewPlayer(p)
	mod:AddHealth(100)
end)

Alternatively, you can add a “char” property to your OOP structure, and make it do the same thing.

1 Like

You shouldn’t do WaitForChild("Character"). Character is a property of the Player, not a child.

2 Likes

Player.Character is not a child of a player, rather a property.

To wait for the character:

local character = player.Character or player.CharacterAdded:Wait()

If the character already exists, then there is no reason to need to wait for it. If it doesn’t, we wait until it is loaded and return it.

It worked now, thank you so much all of you guys, I’m going to investigate until I know enough of OOP! thank you, still I find it maybe not really needed, exchange of self you can just pass trough a function the object but well, I guess it’s another way to do it