it is not really the function, it is the fact that the objects created do not become "pickable" until the next top level event. You could move the actions from the function into the "On start of layout" event and they would still not work.
another way around this is to add a Wait 0 Seconds just before the function call (as long as the fuction call is not inside a loop), because that defers actions after the wait until the end of the current tick... but people usually run into problems implementing that properly, so it would be better to add the extra "On start of layout" event.
if the function call is inside a loop, you can pass the UID of the object to the function and pick the new object by its UID.