Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Calling a Modulescript by a String Variable?

Asked by 3 years 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)
    template:GetTemplate(CharID)
end
--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.

0
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 1336 — 3y
0
Just a through have you got anything like discord or something ? TGazza 1336 — 3y

1 answer

Log in to vote
0
Answered by 3 years 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)
    templates[templateName]:GetTemplate(CharID)
end
0
Thanks a million! This is exactly what I needed. Emdebted 22 — 3y
Ad

Answer this question