WHY npc system can't find instance

Made a metatable oop system thing to try it out. Set empty table to class npc as you do (because i couldnt figure out how to access the original npc in the metatable if i set the original to the class). Works. Set var in metatable to clone of npc instance in storage. Works. Three functions that call each other: first function (Spawn the clone by parenting it to workspace. ) can find this instance, second function can, third function suddely prints nil.

HWat is going on? I dont get this.

output:
00:28:24.148 true - Server - NPCai:28
00:28:24.151 NPC - Server - NPCai:39
00:28:24.153 NPC - Server - NPCai:44
00:28:24.154 nil - Server - NPCai:51


--set the module table metamethod to itself
local NPCai = {}
NPCai.__index = NPCai


-- NPC Constructor 
function NPCai.new()
	
	-- Setup --
	local self = setmetatable({
		
		-- Properties
		
		Hungry = true,	
		Bed = nil,
		ThisNPCinstance = workspace.NPC:Clone()
		
	
	}, NPCai)
	
	print(self.Hungry)
	
	self:spawn()

	
	return self
end


function NPCai:spawn()
	self.ThisNPCinstance.Parent = workspace
	print(self.ThisNPCinstance)
	self:decide()
end

function NPCai:decide()
	print(self.ThisNPCinstance)
	if not self.Bed then
		NPCai:makeBed()
	end
end

function NPCai:makeBed()
	print(self.ThisNPCinstance)
	self.Bed = Instance.new("Part")
	--self.Bed.CFrame = self.ThisNPCinstance.RightUpperLeg.CFrame
	--self.Bed.Parent = workspace
end


return NPCai

Would really appreciate any help. am so confused

What is this magic third function, how are you calling it and what differs to how you are calling first and second functions?

1 Like
function NPCai:decide()
    print(self.ThisNPCinstance)
    if not self.Bed then
        self:makeBed()  -- Use `self` to maintain the correct reference
    end
end

you should use self:makeBed() instead of NPCai:makeBed() within your decide method. I think this should fix your issue, but I am not 100% sure!

1 Like

OH MY GOD.

I bet you’re right. HOW DID I NOT SEE THAT

Thanks so much I’m gonna try this right now

Edit: that was it.
Thanks dude

1 Like

I hadn’t realised I wasn’t calling self: ! Mysterious third function indeed

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.