Certainly! The error you're encountering is due to attempting to use a CFrame where a Vector3 is expected. Specifically, when you get the bounding box of the model, the center is returned as a CFrame, but later in your code, you're treating it as a Vector3.
Here's the corrected code with the necessary changes to fix the issue:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- Configuration
local SPAWN_POSITION = Vector3.new(-15, 19, -63)
local CURRENCY_NAME = "Skira"
local CAMERA_ROTATION_SPEED = 0.5 -- Rotations per second
-- Add missing variables
local ITEMS_FOLDER = ReplicatedStorage:WaitForChild("Spawnable items")
local TEMPLATE_ELEMENT = Players.LocalPlayer.PlayerGui:WaitForChild("Display").Frame.SDS.Frame.List.ItemUI
local ELEMENTS_CONTAINER = Players.LocalPlayer.PlayerGui:WaitForChild("Display").Frame.SDS.Frame.List
-- Required UI elements
local REQUIRED_UI_ELEMENTS = {
"Name",
"Description",
"Optional",
"Buy",
"ItemDisplay"
}
-- Shop items configuration
local ShopItems = {
{
Name = "Blahaj",
Description = "Best, softest, cutest, squishy toy!",
Price = 35,
Limited = false,
New = false
},
{
Name = "Antler",
Description = "Stolen antler that a employee stole after hitting a person",
Price = 75,
Limited = false,
New = false
},
{
Name = "Dynamite",
Description = "An explosive stick filled with a explosive powder.",
Price = 15,
Limited = false,
New = true
},
}
local function CleanModel(model)
local function recursiveClean(instance)
if instance.Name == "Package" then
instance:Destroy()
return
end
if instance:IsA("Script") or
instance:IsA("LocalScript") or
instance:IsA("Sound") or
instance:IsA("StringValue") or
instance:IsA("ModuleScript") or
instance:IsA("RemoteEvent") or
instance:IsA("RemoteFunction") or
instance:IsA("BindableEvent") or
instance:IsA("BindableFunction") then
instance:Destroy()
return
end
if not (instance:IsA("Part") or
instance:IsA("MeshPart") or
instance:IsA("SpecialMesh") or
instance:IsA("Model") or
instance:IsA("Folder")) then
instance:Destroy()
return
end
if instance:IsA("BasePart") then
local originalCFrame = instance:GetAttribute("OriginalCFrame")
local originalPosition = instance:GetAttribute("OriginalPosition")
if originalCFrame then
if typeof(originalCFrame) == "CFrame" then
instance.CFrame = originalCFrame
elseif typeof(originalCFrame) == "Vector3" then
instance.Position = originalCFrame
end
elseif originalPosition then
if typeof(originalPosition) == "Vector3" then
instance.Position = originalPosition
elseif typeof(originalPosition) == "CFrame" then
instance.CFrame = originalPosition
end
end
end
local children = instance:GetChildren()
for _, child in ipairs(children) do
recursiveClean(child)
end
end
recursiveClean(model)
end
-- Function to set up the initial ViewportFrame in the template
local function SetupTemplateViewport()
local template = TEMPLATE_ELEMENT
if not template then
warn("Template not found!")
return
end
local itemDisplay = template:FindFirstChild("ItemDisplay")
if not itemDisplay then
itemDisplay = Instance.new("Frame")
itemDisplay.Name = "ItemDisplay"
itemDisplay.Size = UDim2.new(1, 0, 1, 0)
itemDisplay.BackgroundTransparency = 1
itemDisplay.Parent = template
end
local viewportFrame = Instance.new("ViewportFrame")
viewportFrame.Name = "ViewportFrame"
viewportFrame.Size = UDim2.new(1, 0, 1, 0)
viewportFrame.BackgroundTransparency = 1
viewportFrame.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
viewportFrame.Parent = itemDisplay
local camera = Instance.new("Camera")
camera.Parent = viewportFrame
viewportFrame.CurrentCamera = camera
end
local function SetupItemInViewport(itemDisplay, itemModel)
local existingViewport = itemDisplay:FindFirstChild("ViewportFrame")
if existingViewport then
existingViewport:Destroy()
end
local viewportFrame = Instance.new("ViewportFrame")
viewportFrame.Name = "ViewportFrame"
viewportFrame.Size = UDim2.new(1, 0, 1, 0)
viewportFrame.BackgroundTransparency = 1
viewportFrame.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
viewportFrame.Parent = itemDisplay
local camera = Instance.new("Camera")
camera.Parent = viewportFrame
viewportFrame.CurrentCamera = camera
local modelClone = itemModel:Clone()
CleanModel(modelClone)
modelClone.Parent = viewportFrame
local center = Vector3.new(0, 0, 0)
local size = Vector3.new(0, 0, 0)
if modelClone:IsA("Model") then
local boundingCFrame, boundingSize = modelClone:GetBoundingBox()
center = boundingCFrame.Position
size = boundingSize
elseif modelClone:IsA("BasePart") then
center = modelClone.Position
size = modelClone.Size
end
local maxSize = math.max(size.X, size.Y, size.Z)
local distance = maxSize * 2
local cameraPosition = center + Vector3.new(0, 0, distance)
camera.CFrame = CFrame.new(cameraPosition, center)
local startTime = tick()
local rotationConnection
rotationConnection = RunService.RenderStepped:Connect(function()
if not viewportFrame.Parent or not camera.Parent then
rotationConnection:Disconnect()
return
end
local elapsed = tick() - startTime
local angle = elapsed * (2 * math.pi * CAMERA_ROTATION_SPEED)
local newPosition = center + Vector3.new(
math.cos(angle) * distance,
0,
math.sin(angle) * distance
)
camera.CFrame = CFrame.new(newPosition, center)
end)
end
local function WarnMessage(message)
warn("[Shop System] " .. message)
end
local function ValidateUIElement(template)
local missingElements = {}
for _, element in ipairs(REQUIRED_UI_ELEMENTS) do
if not template:FindFirstChild(element) then
table.insert(missingElements, element)
end
end
if #missingElements > 0 then
WarnMessage(string.format("Missing required UI elements: %s", table.concat(missingElements, ", ")))
return false
end
return true
end
local function ValidateShopItem(itemData)
if type(itemData) ~= "table" then
WarnMessage("Invalid item data format")
return false
end
local requiredFields = {"Name", "Description", "Price"}
for _, field in ipairs(requiredFields) do
if itemData[field] == nil then
WarnMessage(string.format("Missing required field '%s' in item data", field))
return false
end
end
return true
end
local function CreateShopItem(template, itemData)
if not template then
WarnMessage("Shop item template is nil")
return nil
end
if not ValidateShopItem(itemData) then
WarnMessage(string.format("Invalid shop item data for item: %s", itemData.Name or "Unknown"))
return nil
end
if not ValidateUIElement(template) then
WarnMessage("Template validation failed")
return nil
end
local newItem = template:Clone()
local itemDisplay = newItem:FindFirstChild("ItemDisplay")
if itemDisplay then
local itemModel = ITEMS_FOLDER:FindFirstChild(itemData.Name)
if itemModel then
SetupItemInViewport(itemDisplay, itemModel)
else
WarnMessage("Item model not found: " .. itemData.Name)
end
end
local nameLabel = newItem:FindFirstChild("Name")
local descriptionLabel = newItem:FindFirstChild("Description")
local buyButton = newItem:FindFirstChild("Buy")
local optionalLabel = newItem:FindFirstChild("Optional")
if nameLabel then nameLabel.Text = itemData.Name end
if descriptionLabel then descriptionLabel.Text = itemData.Description end
if buyButton then buyButton.Text = tostring(itemData.Price) .. " " .. CURRENCY_NAME end
if optionalLabel then
if itemData.New then
optionalLabel.Text = "New!"
optionalLabel.Visible = true
else
optionalLabel.Visible = false
end
end
if buyButton then
buyButton.MouseButton1Click:Connect(function()
local player = Players.LocalPlayer
local playerMoney = 250 -- Replace with actual money getting logic
if playerMoney < itemData.Price then
return
end
if itemData.Limited then
-- Add limited item availability checking logic here
end
local purchaseEvent = ReplicatedStorage:FindFirstChild("PurchaseItem")
if purchaseEvent and purchaseEvent:IsA("RemoteEvent") then
purchaseEvent:FireServer(itemData.Name)
else
WarnMessage("PurchaseItem RemoteEvent not found or is not a RemoteEvent")
end
end)
end
newItem.Visible = true
newItem.Parent = ELEMENTS_CONTAINER
return newItem
end
local function InitializeShop()
local success, err = pcall(function()
local template = TEMPLATE_ELEMENT
if not template then
error("Shop template not found")
end
SetupTemplateViewport()
template.Visible = false
for _, itemData in ipairs(ShopItems) do
local item = CreateShopItem(template, itemData)
if not item then
WarnMessage(string.format("Failed to create shop item: %s", itemData.Name or "Unknown"))
end
end
end)
if not success then
WarnMessage(string.format("Failed to initialize shop: %s", err))
end
end
InitializeShop()
Explanation of the Fix:
In your SetupItemInViewport function, the issue arises in the following lines:
local center, size = Vector3.new(0, 0, 0), Vector3.new(0, 0, 0)
if modelClone:IsA("Model") then
center, size = modelClone:GetBoundingBox()
elseif modelClone:IsA("BasePart") then
center = modelClone.Position
size = modelClone.Size
end
Here, when modelClone is a Model, GetBoundingBox() returns a CFrame and a Vector3. So, center becomes a CFrame, not a Vector3. Later, you attempt to perform vector arithmetic assuming center is a Vector3, which leads to the error.
Solution:
Modify the code to extract the position from the CFrame when necessary. Here's the corrected portion:
local center = Vector3.new(0, 0, 0)
local size = Vector3.new(0, 0, 0)
if modelClone:IsA("Model") then
local boundingCFrame, boundingSize = modelClone:GetBoundingBox()
center = boundingCFrame.Position
size = boundingSize
elseif modelClone:IsA("BasePart") then
center = modelClone.Position
size = modelClone.Size
end
By extracting the Position from the CFrame, center now correctly holds a Vector3 value, and you can perform vector arithmetic without issues.
Additional Improvements:
-
Connection Cleanup: In the RunService.RenderStepped connection, I've added a check to disconnect the connection if the ViewportFrame or Camera is destroyed, preventing potential memory leaks.
local rotationConnection
rotationConnection = RunService.RenderStepped:Connect(function()
if not viewportFrame.Parent or not camera.Parent then
rotationConnection:Disconnect()
return
end
-- Rest of the code...
end)
-
Consistent Variable Initialization: Ensuring that variables like center and size are always initialized properly helps prevent future errors.
Note: Make sure that the Spawnable items folder in ReplicatedStorage contains models with names matching the Name fields in ShopItems. Also, replace the placeholder for playerMoney with the actual logic to retrieve the player's currency.
Testing the Code:
To ensure the code works as expected:
- Place your item models inside
ReplicatedStorage > Spawnable items with names matching the Name in ShopItems.
- Ensure your UI template (
ItemUI) contains all the required UI elements listed in REQUIRED_UI_ELEMENTS.
- Adjust any paths as necessary based on your game's structure.
Let me know if you have any questions or need further assistance!