Trying to make scripts more efficient

I’m trying to make my scripts more efficient. For example, I wanted to take a script telling an animation to play, and put that in one location so I only have to write the main body of the script once. When I want to play an animation, all I have to do is “call” the script and tell it to place the AnimationId inside the script in the correct place.

However, I don’t know where to put the main body of the script (the part that will only be written out once) or how I could tell the game to place the AnimationId for each animation in that main script.
I know that stuff like ModuleScripts and ServerScriptService, but I have no clue how they work or when to use it.

I have a very basic knowledge of scripting, so please don’t use massively difficult words to understand

2 Likes

Modulescripts are your answer if you want to make an animation player

if you make one you notice how its layout looks something like this

local Table = {}


return Table

Now the way modulescripts work is by requiring

in any script you can do require(modulescript) and this will return the Table shown in the example above.

Inside the body of the modulescript (behind the return) will run when the module was required first

Lets take this and make a function normal scripts can use now

function Table.CreateAnimationById(id)
	--put your main function code now
	--print statement because why not
	return "Something"--returning a string, you might return the animation object instead
end

now lets check in a normal script

local Module = require(Modulescript)

print(Module.CreateAnimationById())
--This would print "Something" as designated by the function above

You can add multiple functions and properties to the module

function Table.FunctionExample()
Table.PropertyExample = "Property"

now since it returns the table and now theres a property lets plug it in to the script

print(Module.PropertyExample)

This would return Property because its what the property example value is

All ServerScriptService is is an internal service from which to run serverscripts (This means instead of running it in the workspace and it being replicated to everyone it just sits in SSS and runs)

ServerStorage however is the exact same thing but scripts inside it don’t run. This service was designed for holding things like maps or things that only the server needs access to.