local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")

local function createWeldConstraint(part0, part1)
	local weld = Instance.new("WeldConstraint")
	weld.Part0 = part0
	weld.Part1 = part1
	weld.Parent = part0
end

local function createMotor6D(part0, part1, name, parent)
	local motor6D = Instance.new("Motor6D")
	motor6D.Part0 = part0
	motor6D.Part1 = part1
	motor6D.Name = name
	motor6D.C1 = CFrame.new(0, 1, 0.5)  -- Set C1 position here
	motor6D.Parent = parent or part0
end



local function weldAllParts(parentPart, primaryPart)
	for _, childPart in parentPart:GetChildren() do
		if childPart:IsA("BasePart") then
			createWeldConstraint(childPart, primaryPart)
		elseif childPart:IsA("Model") then
			weldAllParts(childPart, primaryPart)
		end
	end
end

local function calculateOffsets(parts, basePartName)
	local offsets = {}
	local basePart = parts[basePartName]
	if basePart and basePart.PrimaryPart then
		for _, part in pairs(parts) do
			if part.PrimaryPart then
				offsets[part.Name] = part.PrimaryPart.Position - basePart.PrimaryPart.Position
			end
		end
	end
	return offsets
end

local function weldParts(parts, torso, staticName, colorPartName)
	local offsets = calculateOffsets(parts, staticName)
	local staticPart = parts[staticName]
	if staticPart and staticPart.PrimaryPart then
		staticPart:SetPrimaryPartCFrame(torso.CFrame)
		createWeldConstraint(staticPart.PrimaryPart, torso)
		for name, part in pairs(parts) do
			if name ~= staticName then
				local middlePart = part:FindFirstChild("Middle")
				local colorPart = part:FindFirstChild(colorPartName)
				if name == "Orbs" or name == "Rod" then
					if middlePart then
						-- Creating Motor6D for specific positioning

						-- Weld all parts inside Orbs and Rod to the middle part
						for _, childPart in part:GetChildren() do
							if childPart:IsA("BasePart") and childPart ~= middlePart then
								createWeldConstraint(childPart, middlePart)
							end
						end
					end
				else
					if middlePart and colorPart then
						createWeldConstraint(colorPart, middlePart)
						createWeldConstraint(middlePart, staticPart.PrimaryPart)
						weldAllParts(part, middlePart)
					end
				end
			end
		end
		for name, part in pairs(parts) do
			if part.PrimaryPart and offsets[name] then
				part:SetPrimaryPartCFrame(torso.CFrame * CFrame.new(offsets[name]))
			end
		end
	end
end





ReplicatedStorage.RemoteEvents.MorphRequest.OnServerEvent:Connect(function(player, morph, category)
	local morphTo = ServerStorage.Morphs[category] and ServerStorage.Morphs[category][morph]
	local Character = player.Character
	local torso = Character and (Character:FindFirstChild("Torso") or Character:FindFirstChild("UpperTorso"))

	if morphTo then
		for _, folder in ServerStorage.Morphs[category]:GetChildren() do
			local existingFolder = Character:FindFirstChild(folder.Name)
			if existingFolder then
				existingFolder:Destroy()
			end
		end

		local cloneMorph = morphTo:Clone()
		local parts = {}

		if category == "Ass" then
			parts = {
				LowerL = cloneMorph:FindFirstChild("LowerL"),
				LowerR = cloneMorph:FindFirstChild("LowerR"),
				LowerStatic = cloneMorph:FindFirstChild("LowerStatic")
			}
			for _, part in {"LowerL", "LowerR"} do
				local colorPart = parts[part] and parts[part]:FindFirstChild("color5")
				if colorPart then
					colorPart.Color = Character.Torso.Color
				end
			end
			weldParts(parts, torso, "LowerStatic", "color5")
		elseif category == "Chest" then
			parts = {
				UpperL = cloneMorph:FindFirstChild("UpperL"),
				UpperR = cloneMorph:FindFirstChild("UpperR"),
				UpperStatic = cloneMorph:FindFirstChild("UpperStatic")
			}
			weldParts(parts, torso, "UpperStatic", "color1")
		elseif category == "Pussy" then
			parts = {
				LowerStaticB = cloneMorph:FindFirstChild("LowerStaticB")
			}
			if parts.LowerStaticB and torso then
				parts.LowerStaticB:SetPrimaryPartCFrame(torso.CFrame)
				createWeldConstraint(parts.LowerStaticB.PrimaryPart, torso)
				weldAllParts(parts.LowerStaticB, parts.LowerStaticB.PrimaryPart)
			else
				warn("LowerStaticB or its PrimaryPart not found or set")
			end
		elseif category == "Penis" then
			parts = {
				LowerStaticA = cloneMorph:FindFirstChild("LowerStaticA"),
				Orbs = cloneMorph:FindFirstChild("Orbs"),
				Rod = cloneMorph:FindFirstChild("Rod")
			}

			if parts.Orbs and parts.Orbs.PrimaryPart then
				createMotor6D(torso, parts.Orbs.PrimaryPart, "Motor6D_Orbs", parts.Orbs)  -- Set Orbs as parent
			end

			if parts.Rod and parts.Rod.PrimaryPart then
				createMotor6D(torso, parts.Rod.PrimaryPart, "Motor6D_Rod", parts.Rod)  -- Set Rod as parent
			end

			weldParts(parts, torso, "LowerStaticA", "color5")
		end

		cloneMorph.Parent = Character
	else
		warn("Morph not found for category: " .. category .. ", morph: " .. morph)
	end
end)

1. Modularize the Code: Breakdown large functions into smaller, more modular functions that are easier to test and maintain.

2. Error Handling: Implement more robust error handling. Use conditional checks and assertions to ensure that assumptions in your script are met.

3. Logging: Add logging to help with debugging and understanding the flow of execution. This will simplify understanding what the script is doing at any given point.

4. Constants and Configurations: Store repeated literals and configuration values in constants for easier adjustments and readability.

6. Parameter Validation: Ensure functions are receiving expected parameters, and return early if they don’t meet the required criteria.

7. Reusable Utility Functions: Identify common patterns and utilities in the code, extract them into reusable utility functions.

8. Avoid Deep Nesting: Try to avoid deep nesting of conditionals and loops to improve readability.

9. Optimized Property Access: If multiple accesses to the same property are needed, store the property in a local variable.

10. Use of assert: For critical parts of the code, use assert to ensure conditions are met, which can throw errors if the conditions aren’t satisfied.

11. Enhanced Validation: Include additional checks for the presence and types of objects before performing operations on them.

Here’s a breakdown of how you can apply these suggestions:

### Modularize the Code

Break down large functions like weldParts into smaller helper functions.

### Error Handling

Before accessing properties or calling methods on objects, ensure they exist and fail gracefully if they don’t. Use conditional checks and assertions where necessary.

### Logging

Add print statements or use a logger to log key events, such as when a morph is found, when a weld is created, or when color changes are applied.

### Constants and Configurations

Store repeated strings and configuration values in constants at the top of your script.

### Documentation

Add comments explaining the purpose of each function, the expected parameters, and any important logic within the function.

### Parameter Validation

Validate parameters at the start of each function. If they’re not as expected, log a warning and return early.

### Reusable Utility Functions

Identify repetitive tasks, such as finding children by name or creating welds, and make utility functions for these tasks.

### Avoid Deep Nesting

Refactor deeply nested if-else statements or loops into separate functions to flatten the structure.

### Optimized Property Access

Store frequently accessed properties of objects in local variables to avoid multiple property lookups.

### Use of assert

Use assert to ensure critical logic holds true, for example, ensuring morphTo is not nil or ensuring parts have the expected structure.

### Enhanced Validation

Additional checks should be added to ensure each part and its primary part are valid before performing welding or setting CFrame.

Applying these improvements will make your script more maintainable, readable, and robust.