Top.Mail.Ru
Ответы

Помогите с созданием интерфейса для магазина

Предоставлю вам свои скрипты связанные с проблемой применения одежды на персонажа, у меня следующая задумка: Игрок подходит к примеру к нпс и зажимает E, открывается интерфейса магазина одежда, камера приближает немного скин игрока и смотрит как бы спереди на него, чтоб при выборе одежды к примеру тип одежды: Shirt, при его выборе чтоб футболка на игроке удалялась и одевалась выбранная из Scrolling Frame, правее от него кнопки категории (AccessoriesButton, PantsButton, ShirtsButton) в этом же порядке вертикально, при сохранении выбранная одежда сохраняется на игроке при всех последующих заходах в игру, при закрытии интерфейса, если была выбрана какая-то одежда, то она становится прежней, также я использую DataStorage2, так как собираюсь делать сложную игру, пожалуйста помогите буду очень вам благодарен

Клиентский скрипт:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
local player = game.Players.LocalPlayer
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local shopGui = player.PlayerGui.ClothingShopGui
local shopMenu = shopGui.ShopMenu
local clothesPanel = shopMenu.ClothesPanel
local categoryPanel = shopMenu.CategoryPanel
local templateButton = shopGui.Templates.TemplateButton
local createdButtons = {}

-- Список всех доступных предметов
local outfits = {
	["Shirt"] = {
		["TyeDye"] = {
			AssetId = 7885079797,
		},
	},
	["Pants"] = {
		["Blue Jeans"] = {
			AssetId = 7885083293,
		},
	},
	["Accessories"] = {
		["Cool Hat"] = {
			AssetId = 121296274449810,
		},
		["Glasses"] = {
			AssetId = 6968110631,
		},
	},
}

-- Текущая категория
local currentCategory = "Shirt"

-- RemoteEvents
local wearItemEvent = ReplicatedStorage:FindFirstChild("WearItem")
if not wearItemEvent then
	warn("RemoteEvent 'WearItem' не найден в ReplicatedStorage!")
end

-- Функция очистки GUI
function clearGUI()
	for _, btn in ipairs(createdButtons) do
		btn:Destroy()
	end
	table.clear(createdButtons)
end

-- Функция создания кнопок для выбранной категории
function generateButtonsForCategory(category)
	clearGUI()

	local items = outfits[category]
	if not items then return end

	for name, data in pairs(items) do
		local btn = templateButton:Clone()
		btn.Name = name
		btn.Image = "rbxassetid://116862680140339" -- дефолтное изображение
		btn:SetAttribute("AssetId", data.AssetId)
		btn:SetAttribute("Kind", category:lower()) -- shirt / pants / accessory
		btn.Visible = true
		btn.Parent = clothesPanel
		table.insert(createdButtons, btn)

		btn.MouseButton1Click:Connect(function()
			if wearItemEvent and data.AssetId then
				local kind = btn:GetAttribute("Kind")
				print("Надеваем:", kind, data.AssetId)
				wearItemEvent:FireServer(data.AssetId, kind:sub(1,1):upper()..kind:sub(2))
			else
				warn("Ошибка: RemoteEvent не найден или отсутствует AssetId.")
			end
		end)
	end
end

-- Обработчик клика на категории
function onCategoryButtonClick(category)
	currentCategory = category
	generateButtonsForCategory(category)
end

-- Подключаем события для кнопок категорий
categoryPanel.ShirtButton.MouseButton1Click:Connect(function()
	onCategoryButtonClick("Shirt")
end)

categoryPanel.PantsButton.MouseButton1Click:Connect(function()
	onCategoryButtonClick("Pants")
end)

categoryPanel.AccessoriesButton.MouseButton1Click:Connect(function()
	onCategoryButtonClick("Accessory")
end)

-- Инициализация при открытии магазина
generateButtonsForCategory(currentCategory)

Серверный скрипт:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
local IS = game:GetService("InsertService")
local RS = game:GetService("ReplicatedStorage")
local Http = game:GetService("HttpService")

-- RemoteEvents
local wearEv = Instance.new("RemoteEvent")
wearEv.Name = "WearItem"
wearEv.Parent = RS
print("RemoteEvent WearItem создан")

local quitEv = Instance.new("RemoteEvent")
quitEv.Name = "QuitCustom"
quitEv.Parent = RS
print("RemoteEvent QuitCustom создан")

local saveEv = Instance.new("RemoteEvent")
saveEv.Name = "SaveCustom"
saveEv.Parent = RS
print("RemoteEvent SaveCustom создан")

-- Подключаем DataStore2
local DataStore2 = require(game.ServerScriptService.DataStore2)
DataStore2:SetScope("AvatarSaves") -- аналог GetDataStore

local originals = {} -- таблица оригинальных описаний игроков

-- === WearItem: одеваем штаны/майки/аксессуары ===
wearEv.OnServerEvent:Connect(function(plr, assetId, kind)
	local char = plr.Character or plr.CharacterAdded:Wait()
	local hum = char:FindFirstChildOfClass("Humanoid")
	if not hum then return warn("Humanoid не найден!") end

	originals[plr] = originals[plr] or hum:GetAppliedDescription()

	local desc = hum:GetAppliedDescription()

	if kind == "Shirt" or kind == "Pants" then
		local success, loadedAsset = pcall(IS.LoadAsset, tonumber(assetId))
		if success and loadedAsset then
			local clothingItem = loadedAsset:FindFirstChildOfClass(kind)
			if clothingItem then
				desc[kind] = clothingItem[kind .. "Template"]
			else
				warn("В ассете нет:", kind, assetId)
			end
			loadedAsset:Destroy()
		else
			warn("Ошибка загрузки ассета:", assetId)
		end
	elseif kind == "Accessory" then
		desc.HatAccessory = tostring(assetId) -- Пример: применяем как шляпу
	end

	hum:ApplyDescription(desc)
end)

-- === QuitCustom: отмена кастомизации ===
quitEv.OnServerEvent:Connect(function(plr)
	local char = plr.Character
	if char and originals[plr] then
		local hum = char:FindFirstChildOfClass("Humanoid")
		if hum then
			hum:ApplyDescription(originals[plr])
		end
	end
end)

-- === SaveCustom: сохранение гардероба через DataStore2 ===
saveEv.OnServerEvent:Connect(function(plr)
	local char = plr.Character or plr.CharacterAdded:Wait()
	local hum = char:FindFirstChildOfClass("Humanoid")
	if not hum then return end

	local data = hum:GetAppliedDescription()

	local serializableData = {
		Shirt = data.Shirt,
		Pants = data.Pants,
		Graphic = data.Graphic,

		HatAccessory = data.HatAccessory,
		FaceAccessory = data.FaceAccessory,
		HairAccessory = data.HairAccessory,
		NeckAccessory = data.NeckAccessory,
		ShouldersAccessory = data.ShouldersAccessory,
		FrontAccessory = data.FrontAccessory,
		BackAccessory = data.BackAccessory,
		WaistAccessory = data.WaistAccessory,

		HeadColor = data.HeadColor:ToHex(),
		TorsoColor = data.TorsoColor:ToHex(),
		LeftArmColor = data.LeftArmColor:ToHex(),
		RightArmColor = data.RightArmColor:ToHex(),
		LeftLegColor = data.LeftLegColor:ToHex(),
		RightLegColor = data.RightLegColor:ToHex(),
	}

	local blob = Http:JSONEncode(serializableData)

	-- Сохраняем через DataStore2
	local store = DataStore2("AvatarData", plr.UserId)
	store:Set(blob)
end)

-- === Загрузка при входе ===
game.Players.PlayerAdded:Connect(function(plr)
	local store = DataStore2("AvatarData", plr.UserId)
	local savedBlob = store:Get(nil) -- Получаем сохранённые данные

	if savedBlob then
		local success, savedData = pcall(Http.JSONDecode, Http, savedBlob)
		if success and savedData then
			plr.CharacterAppearanceLoaded:Wait() -- ждём появления персонажа
			local char = plr.Character
			if not char then return end
			local hum = char:WaitForChild("Humanoid", 10)
			if not hum then return end

			local desc = Instance.new("HumanoidDescription")

			for propertyName, value in pairs(savedData) do
				if string.find(propertyName, "Color") then
					if type(value) == "string" then
						desc[propertyName] = BrickColor.new(Color3.fromHex(value))
					end
				elseif desc[propertyName] ~= nil then
					desc[propertyName] = value
				end
			end

			hum:ApplyDescription(desc)
		else
			warn("Не удалось декодировать данные для игрока", plr.UserId)
		end
	end
end)
По дате
По рейтингу
Аватар пользователя
1мес

скачай kali linux