|
| 06 Feb 2017 02:32 PM |
Hello,
I'm struggling to figure out how I can reference a touched object in a simple touching script.
I know how to capture the player that touches my object but I'm not sure how I can reference the object the player has touched which runs the event in the first place.
function collect(hit) local h = hit.Parent:FindFirstChild("Humanoid")
if h then local player = game.Players:GetPlayerFromCharacter(hit.Parent) print("Collecting") _G.score = _G.score+1 print (_G.score) end end
children = game.Workspace:GetChildren() for _, child in pairs(children) do if child.Name == "Coin" then child.Touched:connect(collect)
end end |
|
|
| Report Abuse |
|
|
Roblok1
|
  |
| Joined: 27 Jul 2011 |
| Total Posts: 2019 |
|
|
| 06 Feb 2017 02:41 PM |
here, i made it so you can use 'child' in the same event for each part
children = game.Workspace:GetChildren() for _, child in pairs(children) do if child.Name == "Coin" then child.Touched:connect(function(hit) -- here is the touched function local h = hit.Parent:FindFirstChild("Humanoid") if h then local player = game.Players:GetPlayerFromCharacter(hit.Parent) print("Collecting") _G.score = _G.score+1 print (_G.score) end end) end end
|
|
|
| Report Abuse |
|
|
|
| 06 Feb 2017 06:11 PM |
Thats a great solution!
Thank you so much! |
|
|
| Report Abuse |
|
|
XCVlll
|
  |
| Joined: 23 Oct 2008 |
| Total Posts: 963 |
|
|
| 06 Feb 2017 06:15 PM |
im probably going to get called some pretty mean stuff for this but you can get rid of the first line and just do this:
for _, child in pairs(workspace:GetChildren) do if child.Name == "Coin" then child.Touched:connect(function(hit) -- here is the touched function local h = hit.Parent:FindFirstChild("Humanoid") if h then local player = game.Players:GetPlayerFromCharacter(hit.Parent) print("Collecting") _G.score = _G.score+1 print (_G.score) end end) end end |
|
|
| Report Abuse |
|
|
XCVlll
|
  |
| Joined: 23 Oct 2008 |
| Total Posts: 963 |
|
|
| 06 Feb 2017 06:15 PM |
| forgot the () after GetChildren |
|
|
| Report Abuse |
|
|
|
| 06 Feb 2017 06:45 PM |
Full script for Coin Collecting If anybody else runs into a similar issue.
---Script belongs in ServerScriptService
local totalcoins = 0 _G.score = 0
--while true do
while totalcoins < 40 do coin = Instance.new("Part", workspace) coin.Name="Coin" coin.Shape= game.workspace.Part.Shape coin.Reflectance= 0.4 coin.Material = "Metal" coin.Size = game.workspace.Part.Size coin.Color = Color3.new(0.8,0.6,0.5) coin.Position = Vector3.new(math.random(100),0,math.random(100)) totalcoins = totalcoins+1 end
children = game.Workspace:GetChildren() for _, child in pairs(children) do if child.Name == "Coin" then child.Touched:connect(function(hit) -- here is the touched function local h = hit.Parent:FindFirstChild("Humanoid") if h then local player = game.Players:GetPlayerFromCharacter(hit.Parent) print("Collecting") _G.score = _G.score+1 print (_G.score) child:Destroy() end end) end end
|
|
|
| Report Abuse |
|
|