Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Can't access parts in Workspace using a variable that contains the part's name?

I know the title is a bit weird, but what I mean, is that I've been trying to make a item spawning script similar to Apocalypse Rising's or Deadzone's, and basically, the script uses math.random() to get the name of a random item from a table, then clone the part that corresponds with the item in the table located a few folders down from Workspace. However, I get the error "Chosen is not a valid member of Folder" where I've indicated it below. I have no idea why, and I've been trying and playing around with the script for about an hour now and just can't seem to get it. Also, I've printed the names of the items the script is getting, and they all match perfectly.

function SpawnLoot()
	ClearLoot()

	for i,v in pairs (CivFoodSpawners) do
		local chance = math.random(1,100)
		
		if chance >= 100 - Civ3FoodChance then -- Tier 3 Food
			local Chosen = Civ3Food[math.random(1,#Civ3Food)]
			local Item = game.Workspace.Loot.Food.Chosen -- Error here
			local Clone = Item:Clone()
			Clone.Parent = game.Workspace.ActiveLoot
			Clone.Position = Vector3.new(CivFoodSpawners[i])
		elseif chance >= 100 - Civ2FoodChance then -- Tier 2 Food
			
		else
			
		end
	end
end

Thanks for any help in advance, I'd really appreciate it.

1 answer

✓ Accepted answer

When you say .Chosen, it assumes the child's name is "Chosen", not the string value that the variable is set to. To make this, work, use the Instance function FindFirstChild(). This function will iterate through the children of the Instance it is called on until it finds one with the name of it's first argument, and return that child. If that child doesn't exist, it returns nil.

For example,

local part = workspace:FindFirstChild("Part") --This will return the first child of workspace with the name Part

So in your example you'd just use

local Item = game.Workspace.Loot.Food:FindFirstChild(Chosen)

This should work, assuming the variable Chosen is a string of the objects name. If it is the actual object and not just the name, use

local Item = game.Workspace.Loot.Food:FindFirstChild(Chosen.Name)

This will find the first child of the Food object with the same name as Chosen (Name is a property of Instances)

1 comment

0

It works! Thanks a lot!

This discussion is preserved as it was. New answers, comments, and votes are closed.