Log in to vote

Calling a Modulescript by a String Variable?

Asked by 3 days ago

Hi! Sorry if this is too convoluted or doesn't make much sense, I am very new to scripting and haven't done it in a long time. I'm working on a modulescript that creates an NPC. Since NPCs can be of different types with a large number of different variables, it calls another modulescript while running based on what type of NPC it is asked to make, using the inputs CharID to ensure all NPCs are unique, and template to decide what NPC Template to grab. Telling it to make an NPC right now would look something like NPCProfiler:CreateCharacter(12345,"Human") to make a Human character, as an example.

Here's an example of what I'm doing inside of "NPCProfiler" right now, with unrelated code removed.

local Human = require(game.ServerScriptService.NPCTemplates.Human.HumanTemplate)
local Monster = require(game.ServerScriptService.NPCTemplates.Monster.MonsterTemplate)
--these templates are modulescripts that interact with the model they're in to create the NPC and fill in the data that is not shared between all NPCs like name lists and skin color.

function NPCProfiler:CreateCharacter(CharID,template)
--this is the part of CreateCharacter that is failing, because template:GetTemplate does not work at all, it wants Human:GetTemplate or Monster:GetTemplate, for example.

Basically, I need template:GetTemplate(CharID) to match what the variable template is when CreateCharacter is run and then match with the list of modulescripts defined above (Human, Monster) so it can decide which one of those to run the function GetTemplate from since they all contain one, but this setup fails presumably because template is a string variable. This may be a really simple fix, and I just don't know it, so I'm hoping someone has some insight on a way to make this work.

would you mind posting the module scripts. Just the functions your using for this. It looks like you have a Template handler and a NPCProfiler modulescripts TGazza 608 — 3d
Just a through have you got anything like discord or something ? TGazza 608 — 3d

1 answer

Log in to vote
Answered by 3 days ago

You can use a dictionary indexed with the name of your templates for easy access to the correct template in the CreateCharacter function:

local NPCTemplates = game.ServerScriptService.NPCTemplates

local templates = {
    ["Human"] = require(NPCTemplates.Human.HumanTemplate),
    ["Monster"] = require(NPCTemplates.Monster.MonsterTemplate)

function NPCProfiler:CreateCharacter(CharID, templateName)
Thanks a million! This is exactly what I needed. Emdebted 22 — 3d

Answer this question