This script is for a random weapons crate in my game, however I also have aliens roaming around. When one of these aliens runs into a weapons crate the script instantly breaks with the response : "Alien is not a valid member of Players." How would I make it so that if anything other than a player touches it, the script doesn't break?
script.Parent.Touched:connect(function(hit) script.Disabled = true local player = hit.Parent.Name local random = math.random(1,100) if random > 0 and random < 23 then local laserSword = game.ServerStorage.LaserSword:Clone() laserSword.Parent = game.Players[player].Backpack elseif random > 23 and random < 61 then local sCAR = game.ServerStorage.SCAR:Clone() sCAR.Parent = game.Players[player].Backpack elseif random > 61 and random < 100 then local weapon7 = game.ServerStorage.Weapon7:Clone() weapon7.Parent = game.Players[player].Backpack end script.Parent:Destroy() end) end end)
Use Players:GetPlayerFromCharacter()
and check if it returns nil or not.
local ev ev = script.Parent.Touched:Connect(function(hit) local plr = hit.Parent.ClassName == "Model" and hit.Parent:FindFirstChildOfClass("Humanoid") and game:GetService("Players"):GetPlayerFromCharacter(hit.Parent) if not plr then return --abort if plr is nil end ev:Disconnect() local random = math.random(1,100) if random > 0 and random < 23 then local laserSword = game:GetService("ServerStorage").LaserSword:Clone() laserSword.Parent = plr.Backpack elseif random > 23 and random < 61 then local sCAR = game:GetService("ServerStorage").SCAR:Clone() sCAR.Parent = plr.Backpack elseif random > 61 and random < 100 then local weapon7 = game:GetService("ServerStorage").Weapon7:Clone() weapon7.Parent = plr.Backpack end script.Parent:Destroy() end)
here is an easy three lines:
if not game.Players:GetPlayerFromCharacter(hit.Parent) return end
now, if you want it IN THE CODE, here:
script.Parent.Touched:connect(function(hit) -------- CHECKING FOR PLAYER... -------- if not game.Players:GetPlayerFromCharacter(hit.Parent) return end -- If the script continues from here, the player is not nil. script.Disabled = true local player = hit.Parent.Name local random = math.random(1,100) if random > 0 and random < 23 then local laserSword = game.ServerStorage.LaserSword:Clone() laserSword.Parent = game.Players[player].Backpack elseif random > 23 and random < 61 then local sCAR = game.ServerStorage.SCAR:Clone() sCAR.Parent = game.Players[player].Backpack elseif random > 61 and random < 100 then local weapon7 = game.ServerStorage.Weapon7:Clone() weapon7.Parent = game.Players[player].Backpack end script.Parent:Destroy() end) end end)
If you want to help us here in Masterful Studios (because we NEED it!), please join us here: http://www.roblox.com/My/Groups.aspx?gid=3326074