This can be done pretty simply using UserInputService and CollectionService yet also MarketplaceService for prompting the purchase.
Before doing anything to do with the scripting side of things, make sure to have a NumberValue or IntValue in each block and set it’s Value to the shirt’s ID. Also make sure to use this plugin to add CollectionService tags.
Now firstly, inside your LocalScript which is inside the ScreenGui that contains the two UIs define your dependencies - these will be our services:
-- // Dependencies
local UIS = game:GetService("UserInputService")
local CS = game:GetService("CollectionService")
local MPS = game:GetService("MarketplaceService")
local PLAYERS = game:GetService("Players")
Secondly, define your variables - it’d be a good idea to define the tagged blocks yet also the smallest distance they’ll need to be.
-- // Variables
local TAGGED = CS:GetTagged("TheNameYouTaggedTheBlocks")
local DISTANCE = 2
Thirdly, you’ll need to create the base function to handle the input and compute to wear a shirt or Prompt a purchase of it also the function to loop through and get the nearest shirt if there even is one:
-- // Functions
function searchForClosest()
local closest
for _, block in pairs(TAGGED) do
local magnitude = player.Character and (block.Position - player.Character.HumanoidRootPart.Position).Magnitude or math.huge
if magnitude >= DISTANCE then
DISTANCE = magnitude
closest = block
end
end
return closest
end
function onInput(input, gameProcessedEvent)
if gameProcessedEvent then return end --If they're typing in a TextBox or anything similar then return
if input.KeyCode == Enum.KeyCode.E then
local closest = searchForClosest()
if closest then
player.Character.Shirt.ShirtTemplate = "rbxassetid://" .. closest.NumberValue.Value
end
elseif input.KeyCode == Enum.KeyCode.R then
local closest = searchForClosest()
if closest then
MPS:PromptPurchase(PLAYERS.LocalPlayer, closest.NumberValue.Value)
end
end
end
Forth and finally, connect on InputBegan:
-- // Connections
UIS.InputBegan:Connect(onInput)
You can revise more about these services and magnitude on the developer hub:
If you have any questions or need some more help, be sure to ask!