NewObject usage and setup

Hi Guys,

Got another noob C++ question again… I have the below function: that seems to cause it to crash:

UGrid* AGalaxy::GetGrid(const FVector2D &GetLocation, bool CreateIfMissing)
{
	int N = (GetLocation.X * GalaxySize) + GetLocation.Y;
	UGrid* newGrid = GridLookup[N];
	
	if (!newGrid)
	{
		if (CreateIfMissing == false) return nullptr;
		
		// create an empty Grid data struct if you need one
		GridLookup[N] = NewObject<UGrid>(UGrid::StaticClass());
		newGrid = GridLookup[N];
		//newGrid->SetGridIndex(GetLocation);
	}

	return newGrid;
}

Looking at the debug in VS i get the below which i’m guessing means the UGrid object didn’t create properly but I’m not sure. I can post more code if needed but hopefully it’s an obvious error and this is enough. The VS local look like this when it crashed

Any help would be great, thanks!

The problem is here: GridLookup[N] = NewObject(UGrid::StaticClass());

When you use NewObject to create a UObject, the first parameter to be passed should be the Outer.

For example:
GridLookup[N] = NewObject(this);


Note:
If you want to pass a specific child class for this object, then pass the class name as the second parameter.
For example:
You have a BluePrint, which extends the UGrid, called BP_Grid.
In the BP_Grid you change parameters and input values that you want to use in the game.
In order to create objects using the BP_Grid, you have to pass the BP_Grid as class, then create objects using the BPGridClass:
GridLookup[N] = NewObject(this, BPGridClass);

The BPGridClass declaration in the .h file:
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSubclassOf BPGridClass;