For your first question, let’s say I have an animal. The player then damages the animal. What I would’ve done previously is that the player attack script would calculate the damage and then change the animal’s humanoid’s health.
However, that would be very inefficient, since each thing that is meant to damage the animal would have to have the piece of code responsible for damage in them, creating a lot of repetition, not to mention how complicated things would get if there was a different type of animal that calculated damage differently.
What I would do now is that when the player attacks the animal, the player attack script would run some kind of damage function that is found inside the animal ai script, however I can’t do that with a normal script, the only ways I can think of is to use a module script, however, module scripts cannot itself run code, meaning that I cannot run AI.
Even if I do use a module script for each animal, I imagine that would be quite memory inefficient, considering I am cloning the script for each time a new animal spawns. The best solution to this would be classes, since I will be able to use the same functions for each animal without replicating them and using up memory.
This leads to your second question. I found that metatables can be used similar to classes when done like this:
-- inside a module script
local EntityClass= {}
EntityClass.__index = EntityClass
function EntityClass.new()
local instance = setmetatable({},EntityClass)
instance.health = 100
return instance
end
function EntityClass:Damage(damageAmount)
self.health -= damageAmount
end
return EntityClass
An object of the EntityClass can then be created in another script like this:
local animalClass = require(module I showed above)
local animal = animalClass.new()
animal:Damage(20)
The problem is that I don’t know how I would make this work with the animal. When the player attack script is meant to attack the animal, I am not sure how I would get the animal object and then call the Damage function in a way that isn’t very clunky. Of course, keep in mind that I am not sure if this approach of using metatables for animals is even the best way out there.