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

How to use variable when looking for a part?

Sorry if my title doesn't make sense. i don't know what what i'm trying to do is called.

i'm making a way to place trees and harvest fruits of them. The trees can be placed by the player. When they place it my first script places the tree and names it to tree(number). For every tree placed the number increases by one, so they all have unique names.

My second script lets the player click E when near the tree to harvest it. It does this by checking the list of trees and when its found a tree within 10 studs of the player makes the fruit drop for them to pick up. Here is the code for making the fruit drop.


local treenumber = 0   --treenumber is the amount of trees checked
TreeValue = game.ReplicatedStorage.TreeValue.Value

wait(1)
local Player = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")
local UserInputService = game:GetService("UserInputService")



UserInputService.InputBegan:Connect(function(keyCode)
		if keyCode.KeyCode == Enum.KeyCode.E then     --when e is pressed
			
			print ("E detected")        --verify e was clicked
			local treecount = TreeValue.Value   --treecount is the amount of trees in the game
			
			while treenumber < treecount do      --while the number of trees is bigger than the amount of trees checked
					
					print ("checking trees")   --verify checking trees
					local treename = ("tree".. treenumber)  --set the treename to the current tree name being checked
					print (treename)          --verify
					wait(3)
					local tree = game.Workspace.Base.ItemHolder.treename    --set tree variable value to a certain tree
					treenumber = treenumber + 1         --add one to the amount of trees checked and check the next tree on next loop
					
					if (tree.Position - Player.Position).magnitude < 10 then  --if player is close to tree                       
						wait(0.1)
						print ("shake from tree"..treenumber)  --verify that shake has been detected
			
			end
			

		end
		
			end
end)


Here is the error it gives me: "treename is not a valid member of Model" on line 22. The code is searching for the name of the variable (treename), not the value of it(tree1). How do i fix this?

Sorry if my code or explanation is hard to read.

1 answer

Instead of game.Workspace.Base.ItemHolder.treename type game.Workspace.Base.ItemHolder[treename] like it were a dictionary/table :

game = { --game
	Workspace{ --game.Workspace
		Base  = { --game.Workspace.Base
			ItemHolder = { --game.Workspace.ItemHolder
				Tree = {...} --game.Workspace.Itemholder.Tree
			};
		};
	};
	... = {
		...
	}...
}

so you basiacally just think of it like a Dictionary ignore if it didn't make sense

1 comment

0

Thank you SO much!!!! :D

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