This is a script I made that randomly picks what type of person the NPC is from a table. There are three classes; MemeGuy1, Customer1, and BusinessMan, This script randomly picks one of them and then I want it to assign a shirt according to what NPC class is selected. How can I do this because when I tried, it returns an error. Problem is on the last line, how do I fix this?
local npc = script.Parent NPCs = {'MemeGuy1', 'Customer1', 'BusinessMan'} MemeGuy1 = {'rbxassetid://2022860286'} Customer1 = {'rbxassetid://2022860286'} BusinessMan = {'rbxassetid://2022860286'} math.randomseed(tick()) NPCNum = math.random(#NPCs) selectedNPC = NPCs[NPCNum] local npcShirt = Instance.new("Shirt",npc) npcShirt.ShirtTemplate = (selectedNPC[1]) ---PROBLEM
Firstly, if you care about performance at all, do not assign the parent in the Instance.new("Shirt", npc)
call. It's better to use local shirt = Instance.new("Shirt")
then assign the parent afterwards: shirt.Parent = npc
. You can read more about that here if you like.
Anyways, the problem here is that you are assigning the shirt to the wrong thing.
On line 15 you wrote: selectedNPC = NPCs[NPCNum]
which would return either 'MemeGuy1'
, 'Customer1'
or 'BusinessMan'
. Note how they are all string objects. Then, you are trying to index the first element of that string, thinking it is actually a table.
In order to solve this, you would need to put your variables MemeGuy1
, etc. into a table, then index that table. For example:
local npc = script.Parent -- no need to assign each one to a table of length one, instead just assign it to the string object MemeGuy1 = 'rbxassetid://...' Customer1 = '...' BusinessMan = '...' -- fill these with their respective rbxassetids NPCs = {MemeGuy1, Customer1, BusinessMan} -- putting variables instead of strings that match variable names math.randomseed(tick()) NPCNum = math.random(#NPCs) selectedNPC = NPCs[NPCNum] local npcShirt = Instance.new("Shirt") npcShirt.ShirtTemplate = selectedNPC npcShirt.Parent = npc
This should fix the issue.
EDIT:
Another possible solution - one that I would personally choose - is creating a table of tables. That way, you will be able to select a random NPC and still be able to define properties to each NPC such as name, shirtTexture, etc. This would allow your code to be easily upgrade-able if you needed to, for example, add an Age property to every NPC.
Here's what I mean:
local NPCs = { { NPCName = 'MemeGuy1', ShirtTexture = 'rbxassetid://...' }, { NPCName = 'Customer1', ShirtTexture = 'rbxassetid://...' } } math.randomseed(tick()) selectedNPC = math.random(#NPCs) local npcShirt = Instance.new("Shirt") npcShirt.ShirtTemplate = NPCs[selectedNPC].ShirtTexture npcShirt.Parent = npc