Create Object Function Not Working

I found source code for a CreateObject Function to make creating objects cleaner and easier, it works when I use it in the script itself, but I threw it in a module in ReplicatedStorage and now when I use it it doesn’t work.
Here is the code for the function and how it’s used

--Function
function Utilities:CreateObject(InstanceData)
	print(InstanceData)
	return function(data)
		local Object = Instance.new(InstanceData)
		for a, b in pairs(data) do
			local c, d = pcall(function()
				if type(a) == "number" then b.Parent = Object
				elseif type(b) == "function" then Object[a]:connect(b)
				else Object[a] = b end
			end)
			if not c then
				warn("ERROR: Applying property '"..a.."' to "..InstanceData.." failed! ("..d..")")
			end
		end
		return Object
	end
end
--Usage Example
local Background = CreateObject "Frame" {
	BackgroundColor3 = Color3.new(0.0, 0.0, 0.0),
	Size = UDim2.new(1.0, 0, 1.0, 0),
	Parent = Gui}

Here is the output when I use it in the module:


Anybody know how I could make this work now?

1 Like

For your module script you need to write it like this:

local Utilities = {}
function Utilities:CreateObject(InstanceData)
	print(InstanceData)
	return function(data)
		local Object = Instance.new(InstanceData)
		for a, b in pairs(data) do
			local c, d = pcall(function()
				if type(a) == "number" then b.Parent = Object
				elseif type(b) == "function" then Object[a]:connect(b)
				else Object[a] = b end
			end)
			if not c then
				warn("ERROR: Applying property '"..a.."' to "..InstanceData.." failed! ("..d..")")
			end
		end
		return Object
	end
end
return Utilities --// Return the module table

Then in another script you can write:

local Utilities = require(game.ReplicatedStorage.Modules.Utilities) --// Wherever you put the module script
local Background = Utilities:CreateObject "Frame" {
	BackgroundColor3 = Color3.new(0.0, 0.0, 0.0),
	Size = UDim2.new(1.0, 0, 1.0, 0),
	Parent = Gui}

I have done this, I was curious about the error tho, so I made it print InstanceData and it returns nil. While if this is used in the script itself it returns the object.

In the script calling the module try changing it to this:

local Utilities = require(game.ReplicatedStorage.Modules.Utilities) --// Wherever you put the module script
local Background = Utilities:CreateObject("Frame")({
	BackgroundColor3 = Color3.new(0.0, 0.0, 0.0),
	Size = UDim2.new(1.0, 0, 1.0, 0),
	Parent = Gui})

I think the problem is that to call a function you need the parenthesis. Hope this helps.

I’m sorry but it still returns nil. But Maybe it’s because the module script that’s using the function is being cloned from serverstorage to replicated storage where the utilities are being used.