How would i improve this interaction system

So i made a interaction system how could i improve it?

-- Player Itself
local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character
local Humanoid = Character:WaitForChild("Humanoid")

-- Variables
local UserInputService = game:GetService("UserInputService")

--Interactions
local InteractionFolderName = game.Workspace.Interactions:GetChildren()


UserInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.E then
		for Interaction, Interact in pairs(InteractionFolderName) do
			if Interact:IsA("BasePart") then
				local PlayerDistance = Player:DistanceFromCharacter(Interact.Position)
				if Interact.Name == "TriggerOne" and PlayerDistance <= 10 then 
					print("TriggerOne")
				else if Interact.Name == "TriggerTwo" and PlayerDistance <= 10 then
						print("TriggerTwo")
					end
					
				end
			end
		end
	end
end)
2 Likes

Hi, so there is what I would do differently (see code below). Also, keep in mind I am not an advanced scripter, so this is just my opinion:

  • Use :WaitForChild("Interactions") so the code won’t break if the folder’s still loading;
  • Use local Character = Player.Character or Player.CharacterAdded:Wait() so the code works even if the player’s character won’t be loaded yet;
  • Instead of checking for each interaction, I would just check FIRST for the distance for each interaction and then do some action for it, maybe this could be done with OOP; but with this point, I’m not so sure because I don’t really know how you use the Interactions;
  • And last thing, I think ContentActionService is more actual than UIS and you can also work with it on devices like mobile, and it has few other advantages
-- Player Itself
local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")

-- Variables
local UserInputService = game:GetService("UserInputService")

--Interactions
local InteractionFolderName = game.Workspace:WaitForChild("Interactions"):GetChildren()


UserInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.E then
		for Interaction, Interact in pairs(InteractionFolderName) do
			if Interact:IsA("BasePart") then
				local PlayerDistance = Player:DistanceFromCharacter(Interact.Position)
			
			    if Player:DistanceFromCharacter(Interact.Position) <= 10 then
			        
			        print(Interact.Name)
			   end
			end
		end
	end
end)

Anyways, hope my points will help you! You might not fully agree with them, this is just what I would do. Have a nice day! :blue_heart:

3 Likes