Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

Roblox Studio програмирование

Rocket launcher team Ученик (116), открыт 1 день назад
Почему у меня не хочет работать проверка куплен ли геймпас
 local ms = game:GetService("MarketplaceService") 

game.Players.PlayerAdded:Connect(function(plr)
-- Вот он не определяет почему?
if ms:UserOwnsGamePassAsync(plr.UserId, 1064646395) then
script.Parent.Text = "Gold"
else
script.Parent.Text = "Gold (100 R)"
end

script.Parent.MouseButton1Click:Connect(function()
if ms:UserOwnsGamePassAsync(plr.UserId, 1064646395) then
script.Parent.Text = "Gold"
local parts = game.Workspace.Rock:GetChildren()
for i = 1, #parts do
local part = parts[i]

if part:IsA("Part") then
part.Transparency = 1
end

game.Workspace.Rock.Gold.Transparency = 0
end
else
script.Parent.Text = "Gold (100 R)"
ms:PromptGamePassPurchase(plr, 1064646395)
end
end)
end)
2 ответа
{ { Ученик (232) 1 день назад
Твоя проблема, скорее всего, связана с тем, что функция `UserOwnsGamePassAsync` работает асинхронно, и результат её выполнения не доступен сразу. Это значит, что ты пытаешься использовать результат проверки владельца геймпаса до того, как она завершится.

Чтобы исправить это, нужно использовать `await` или обработку результата с помощью функции `callback`, чтобы убедиться, что результат проверки доступен перед продолжением выполнения кода.

Вот исправленная версия твоего кода с использованием `:andThen` для обработки асинхронного вызова:

```lua
local ms = game:GetService("MarketplaceService")

game.Players.PlayerAdded:Connect(function(plr)
-- Используем асинхронную проверку через :andThen
ms:UserOwnsGamePassAsync(plr.UserId, 1064646395):andThen(function(hasGamePass)
if hasGamePass then
script.Parent.Text = "Gold"
else
script.Parent.Text = "Gold (100 R)"
end

script.Parent.MouseButton1Click:Connect(function()
ms:UserOwnsGamePassAsync(plr.UserId, 1064646395):andThen(function(hasGamePass)
if hasGamePass then
script.Parent.Text = "Gold"
local parts = game.Workspace.Rock:GetChildren()
for i = 1, #parts do
local part = parts[i]
if part:IsA("Part") then
part.Transparency = 1
end
end
game.Workspace.Rock.Gold .Transparency = 0
else
script.Parent.Text = "Gold (100 R)"
ms:PromptGamePassPurchase(plr, 1064646395)
end
end)
end)
end)
end)
```

Что изменилось:

1. Вместо того, чтобы сразу использовать `ms:UserOwnsGamePassAsync()`, я использую `:andThen`, чтобы гарантировать, что результат будет получен до выполнения следующего шага. Это нужно, чтобы асинхронная операция завершилась перед продолжением выполнения кода.
2. Для проверки геймпаса используется обработчик результата внутри `andThen`, что позволяет корректно отработать логику.

Теперь код должен корректно проверять, есть ли у игрока геймпасс, и на основе этого выполнять дальнейшие действия.
Rocket launcher teamУченик (116) 1 день назад
Всё равно не работает
Илья Ротков Мыслитель (6070) 1 день назад
Попробуй этот код:
 local ms = game:GetService("MarketplaceService") 
local Players = game:GetService("Players")

local gamePassID = 1064646395
local button = script.Parent

local function updateButtonText(player)
local success, ownsPass = pcall(ms.UserOwnsGamePassAsync, ms, player.UserId, gamePassID)

if success and ownsPass then
button.Text = "Gold"
else
button.Text = "Gold (100 R)"
end
end

Players.PlayerAdded:Connect(function(player)
if player == Players.LocalPlayer then
updateButtonText(player)
end
end)

if Players.LocalPlayer then
updateButtonText(Players.LocalPlayer)
end

button.MouseButton1Click:Connect(function()
local player = Players.LocalPlayer

if player then
local success, ownsPass = pcall(ms.UserOwnsGamePassAsync, ms, player.UserId, gamePassID)

if success and ownsPass then
print("Игрок владеет геймпасом!")
button.Text = "Gold"

local rockParts = game.Workspace.Rock:GetChildren()
for _, part in ipairs(rockParts) do
if part:IsA("Part") then
part.Transparency = 1
part.CanCollide = false
end
end
local goldPart = game.Workspace.Rock:FindFirstChild("Gold")
if goldPart and goldPart:IsA("Part") then
goldPart.Transparency = 0
goldPart.CanCollide = true
end

else
print("Игрок не владеет геймпасом, предлагаем покупку.")
button.Text = "Gold (100 R)"
ms:PromptGamePassPurchase(player, gamePassID)
end
end
end)

ms.PromptGamePassPurchaseFinished:Connect(function(player, purchasedGamePassID, wasPurchased)
if player == Players.LocalPlayer and purchasedGamePassID == gamePassID then
if wasPurchased then
print("Геймпас успешно куплен!")
updateButtonText(player)
local rockParts = game.Workspace.Rock:GetChildren()
for _, part in ipairs(rockParts) do
if part:IsA("Part") then
part.Transparency = 1
part.CanCollide = false
end
end
local goldPart = game.Workspace.Rock:FindFirstChild("Gold")
if goldPart and goldPart:IsA("Part") then
goldPart.Transparency = 0
goldPart.CanCollide = true
end

else
print("Покупка геймпаса не завершена или отменена.")
updateButtonText(player)
end
end
end)
Похожие вопросы