我正在尝试在 Roblox Studio 中编写猎枪代码。该代码不起作用,因为它没有得到枪。当它激活时,应该装备枪。
我尝试了很多不同的方法来从玩家的角色中获取枪,包括“:WaitForChild”和for循环,但它们从未最终起作用。 这是我的代码:
local players = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local function getEquippedTool(player: Player): Tool?
local character = player.Character
if not character then
print("no character")
return nil
else
local shotgun = character:WaitForChild("Shotgun")
if not shotgun then
print("no shotgun")
return nil
else
print("success")
return shotgun
end
end
end
replicatedStorage:WaitForChild("ShotgunShoot").OnServerEvent:Connect(function(plr,part,pos,damage)
print("Server: Triggered")
local char = plr.Character
local tool = getEquippedTool(plr)
if tool == nil then
print("tool doesnt exist")
else
print(tool.Name)
local handle = tool:WaitForChild("Handle")
if part then
print("part=true")
if part.Parent and part.Parent:FindFirstChild("Humanoid") then
local humanoid = part.Parent.Humanoid
humanoid:TakeDamage(damage)
print("HIT")
else
print("MISS")
local bullet = Instance.new("Part")
bullet.Size = Vector3.new(0.1,0.1,0.1)
bullet.Position = pos
bullet.BrickColor = BrickColor.Black()
bullet.Anchored = true
bullet.CanCollide = false
bullet.Parent = workspace
game.Debris:AddItem(bullet, 5)
end
end
if handle:FindFirstChild("ShotgunSound") then
local sound = handle.ShotgunSound
sound:Play()
end
end
end)
有人可以帮我解决这个问题吗? 编辑:为了澄清,函数
getEquippedTool()
正在返回nil
,我希望它返回player.Character.Shotgun
,我知道在运行脚本时配备了它。
因为,我还不能发表评论......这是服务器脚本还是本地脚本?脚本返回 nil 是什么意思?我相信角色不是玩家的孩子,你必须按照以下方式执行命令:GetPlayerFromCharacter