Roblox脚本if语句报错:Unable to cast string to int64问题求助
解决Roblox徽章脚本
Unable to cast string to int64错误 错误原因
你遇到的Unable to cast string to int64错误,是因为BadgeService的UserHasBadgeAsync和AwardBadge方法要求第二个参数是整数类型的徽章ID,但你直接传入了TextBox.Text(字符串类型),系统无法自动把任意字符串转成整数,所以触发报错。另外你的条件判断逻辑搞反了——现在代码是“玩家已有徽章就颁发”,和你要的“无需解锁直接获取”需求不符。
修复方案
- 将
TextBox.Text转换为整数类型后再传入方法 - 修正条件判断逻辑,改成“玩家没有徽章时颁发”
- 增加输入合法性判断,避免非数字输入导致报错
- 用
pcall包裹徽章服务调用,防止脚本因异常崩溃
修正后的Script代码
local badgeservice = game:GetService("BadgeService") local warning = false script.Parent.MouseButton1Click:Connect(function() if not warning then warning = true -- 通过UserId获取玩家对象,比直接用UserId更安全 local player = game.Players:GetPlayerByUserId(script.Parent.Value.Value) if not player then script.Parent.Parent.TextLabel.Text = "玩家不存在!" wait(3) script.Parent.Parent.TextLabel.Text = "输入徽章ID后点击GIVE直接获取对应徽章" warning = false return end -- 把输入的文本转成整数,判断是否为有效数字 local badgeId = tonumber(script.Parent.Parent.TextBox.Text) if not badgeId then script.Parent.Parent.TextLabel.Text = "请输入有效的数字徽章ID!" wait(3) script.Parent.Parent.TextLabel.Text = "输入徽章ID后点击GIVE直接获取对应徽章" warning = false return end -- 用pcall包裹徽章检查,避免异常崩溃 local hasBadge, checkErr = pcall(function() return badgeservice:UserHasBadgeAsync(player.UserId, badgeId) end) if hasBadge then if not hasBadge then -- 玩家没有徽章时尝试颁发 local success, awardErr = pcall(function() badgeservice:AwardBadge(player.UserId, badgeId) end) if success then script.Parent.Parent.TextLabel.Text = "徽章颁发成功!" else script.Parent.Parent.TextLabel.Text = "颁发失败:" .. awardErr end else script.Parent.Parent.TextLabel.Text = "你已经拥有这个徽章了!" end else script.Parent.Parent.TextLabel.Text = "检查徽章状态失败:" .. checkErr end wait(3) script.Parent.Parent.TextLabel.Text = "输入徽章ID后点击GIVE直接获取对应徽章" warning = false end end)
额外说明
原LocalScript代码无需修改,但ServerScript里通过GetPlayerByUserId获取玩家对象,能避免玩家离线等异常情况。
内容的提问来源于stack exchange,提问作者Alexia
相关产品推荐
相关产品推荐

