Extending from Object

Hi All,

C++ noob here. I am fairly well-versed in Unrealscript, but new to C++.

I would appreciate some answers on the following, but first some backstory:

I have created a simple class (header and cpp files) that I would ideally like to extend from Object instead of Actor, as it doesn’t require any physical presence in the world. I require an instance/reference/pointer of/to this class in my custom Character class to handle some calculations.

Coming from Unrealscript, I couldn’t figure out the C++/UE4 equivalent of

var MyObject MyObjectRef;

MyObjectRef = new class'MyObject';

so I extended my class from Actor and used:


AMyObject *MyObjectPointer


MyObjectPointer = World->SpawnActor<AMyObject>(AMyObject::StaticClass(), etc);

This seems to work. However, I would like to know:

  1. How would I go about doing this when extending from Object instead, i.e. declaring the variable and creating a reference/instance of my object in MyCharacter.cpp. Please remember I’m a noob so feel free to be as verbose as possible.
  2. Is this always how you’d go about spawning actor classes, i.e. working with the pointer to the instance (returned by “SpawnActor”) instead of an actual instance?

Any feedback would be greatly appreciated.

You should be able to just use NewObject or NewNamedObject to achieve the same effect.

Hi kopirat,

Thanks very much for the quick response.
I’ve had a read through the documentation you’ve linked to, and it’s solved my initial problem. It seems the Editor crash is related to the call to


without checking for GEngine being null, and not to how I instantiated the object. For reference, all details below:

I’ve generated a new class via the editor called “PWNTestObject”, which gave me the header and source files, to which I added the following:


// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "Object.h"
#include "PWNTestObject.generated.h"

class UPWNTestObject : public UObject

	float TestMe(float TestVal);	


// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.

#include "PWNGame.h"
#include "PWNTestObject.h"

UPWNTestObject::UPWNTestObject(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)

float UPWNTestObject::TestMe(float TestVal)
	return TestVal * 2.0f;

Now in the class from which I want to spawn this, I do:


UPWNTestObject *TestObject;


APWNPlayerCharacter::APWNPlayerCharacter(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
	TestObject = NewObject<UPWNTestObject>(this, UPWNTestObject::StaticClass());
	// Uncommenting this line below crashes the editor
	//GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, FString::SanitizeFloat(TestObject->TestMe(50.0f)));


Fix is to use

if (GEngine)
		GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, FString::SanitizeFloat(TestObject->TestMe(50.0f)));