Creation of UObjects outside the game thread

Sorry for necro-ing this. But I’ve had this problem and I found a solution that works for 5.4.

I know about the async flag but it was causing issues, so I needed a more reliable method of creating the objects.

template<typename T>
T* NewObjectAnyThread()
{
	UObject* OutObject;
	bool bObjectCreated = false;

	TFunction<void()> CreateObject = [&OutObject, &bObjectCreated]
	{
		OutObject = NewObject<T>();
		bObjectCreated = true;
	};

	if (IsInGameThread())
	{
		CreateObject();
	}
	else
	{
		AsyncTask(ENamedThreads::Type::GameThread, [this, &CreateObject]
		{
			CreateObject();
		});

		FPlatformProcess::ConditionalSleep([this, &bObjectCreated]
		{
			return bObjectCreated;
		}
		, .05f);
	}

	check(IsValid(OutObject))
	return OutObject;
}

Note: Checking IsValid inside the conditional sleep condition resulted in a stale object for some reason.
The usage of busy waiting here is (arguably) justified since creating a UObject is a rather fast and only needs to be done once for creating the object.

This method worked flawlessly the 2 times I tested it while creating 5 objects in a for loop.

I didn’t try to decrease the sleep time, I was too afraid to push any boundaries.