How to receive message in factory created instance?

I’m trying to get a barebones message passing example worked out and I’m having some trouble.

In the main collection I have one object with a script component and a factory component. The factory component creates a different game object that has a script component.

In the sript component for object1 I have this:

function init(self)

print("This object exists in running collection! This is object1!")

--[[
local function timed_action()
	print("Timer fired in object1!")
	local this_data = "this is data"
	print(self.reference_to_object2.."#object2")
	msg.post(self.reference_to_object2, "fire", { this_data })
end
--]]

local object2 = factory.create("#create_object2s")

local this_data = "this is data"
msg.post(object2, "fire", { this_data }) -- this one doesn't show an error, but the on_message function doesn't fire in object2
msg.post("/Collection#object2", "fire", { this_data }) -- this one fires an error 
self.reference_to_object2 = object2


--local inst_timer = timer.delay(2, true, timed_action)
end

And for object2:

function init(self)

print("This is object2!")

function on_message(self, message_id, message, sender)
	print("message received")
	print(message_id) --> hash: [my_message_name]

	pprint(message) --> {
	-->   score = 100,
	-->   value = "some string"
	--> }

	print(sender) --> url: [main:/my_object#script]
end
end

The output:

DEBUG:SCRIPT: This object exists in running collection! This is object1!
DEBUG:SCRIPT: This is object2!
ERROR:GAMEOBJECT: Instance '/Collection' could not be found when dispatching message 'fire' sent 
from main:/object1#object1

It looks like my first message is being delivered or failing silently.

I’ve been perusing the docs and forum, but could really use some help here.

Any idea what I’m doing wrong?

Looks like you’ve accidentally nested your on_message function inside on_init in object2.

function init(self)

print("This is object2!")

end

function on_message(self, message_id, message, sender)
	print("message received")
	print(message_id) --> hash: [my_message_name]

	pprint(message) --> {
	-->   score = 100,
	-->   value = "some string"
	--> }

	print(sender) --> url: [main:/my_object#script]
end
1 Like
msg.post("/Collection#object2", "fire", { this_data }) -- this one fires an error 

This doesn’t seem correect, # is for referencing components
Try to pass it as url:
msg.post(msg.url(nil, object2, "script") , "fire", {this_data = this_data}) or something like that.

1 Like

I should have mentioned that the expected outcome does include the Error:GAMEOBJECT line, but for the post that does go through why aren’t the print lines in on_message showing in the console?

I tested outside of the init function and the output is the same.

Oof, just realized the script is auto populated with an on_message function that I hadn’t removed. So, this is working now. Thanks all.

3 Likes