First, if you have many similar objects, it's a great idea to put them all in an array. This allows you to access a light switch based on it's number in the array, like so:
1 | local lightSwitches = { workspace.LightSwitch 1 , |
2 | workspace.LightSwitch 2 , |
3 | workspace.LightSwitch 3 , |
4 | workspace.LightSwitch 4 , |
5 | workspace.LightSwitch 5 } |
Alternatively, you can automate discovery of your lights, using a for-each loop. Don't do this too often, as it is quite expensive. To be more efficient, you could put all your lights into a common folder you could quickly scan through. To do this, you should name them all the same thing. It's not important for you to be able to distinguish between light switches, so this is by far the easiest solution.
01 | local placeWithAllLights = workspace.folderWithLights |
03 | local lightSwitches = { } |
04 | for index, object in pairs (placeWithAllLights:GetChildren()) do |
05 | if object.Name = = "LightSwitch" then |
06 | table.insert(lightSwitches, object) |
07 | print ( "This is a light!" ) |
12 | print ( "Finished scanning for lights, found " , #lightSwitches) |
This should give you an array with all of your lights in it. Then, it's a simple matter of scanning through lights when E is pressed, and finding the closest one. This is what it would look like finished:
01 | local placeWithAllLights = workspace.folderWithLights |
03 | local lightSwitches = { } |
04 | for index, object in pairs (placeWithAllLights:GetChildren()) do |
05 | if object.Name = = "LightSwitch" then |
06 | table.insert(lightSwitches, object) |
07 | print ( "This is a light!" ) |
12 | print ( "Finished scanning for lights, found " , #lightSwitches) |
14 | local nearestLightSwitchIndex |
15 | local nearestLightDistance = math.huge |
18 | UIS.InputBegan:Connect( function (input) |
19 | if input.KeyCode = = Enum.KeyCode.E then |
20 | for index, lightSwitch in pairs (lightSwitches) do |
21 | local distance = (chr.Torso.Position - lightSwitch.Switch.Position).magnitude |
22 | if distance < = range and distance < nearestLightDistance then |
23 | nearestLightSwitchIndex = index |
24 | nearestLightDistance = distance |
28 | remote:FireServer( tostring (nearestLightSwitchIndex )) |
I HIGHLY recommend reading up on for loops and generic for loops, as well as tables/array. They can make life a million times easier in the long run. Hope I helped!
http://wiki.roblox.com/index.php?title=Loops
http://wiki.roblox.com/index.php?title=Generic_for
http://wiki.roblox.com/index.php?title=Table