Download

Crash when trying to change variable in UObject

Hey there.

My code is crashing at Obj.cpp


Test = 10;

. Anybody have any idea why its crashing?
Im not any good at c++(or ue4 in general) so any help would be appreciated much.

MyActor.cpp



#include "objtest.h"
#include "MyActor.h"

AMyActor::AMyActor()
{
	PrimaryActorTick.bCanEverTick = true;
}

void AMyActor::BeginPlay()
{
	Super::BeginPlay();
	Obj->SetTestG();
}
void AMyActor::Tick( float DeltaTime )
{
	Super::Tick( DeltaTime );
}


MyActor.h



#pragma once

#include "GameFramework/Actor.h"
#include "Obj.h"
#include "MyActor.generated.h"

UCLASS()
class OBJTEST_API AMyActor : public AActor
{
	GENERATED_BODY()
public:	
	AMyActor();
	virtual void BeginPlay() override;
	virtual void Tick( float DeltaSeconds ) override;

	UObj* Obj;
};


Obj.h



#pragma once

#include "UObject/NoExportTypes.h"
#include "Obj.generated.h"

UCLASS()
class OBJTEST_API UObj : public UObject
{
	GENERATED_BODY()
public:
	int32 Test = 0;
	void SetTestG();
};



Obj.cpp



#include "objtest.h"
#include "Obj.h"


void UObj::SetTestG() {
	Test = 10;
}


EDIT1: Compile/Build is fine, but it crashes on play

You never set obj in your AMyActor class, so its null when you call SetTestG

Thx for help.
Seems like



Obj = NewObject<UObj>(this, FName("Obj"));


did the trick. Not sure if thats the right why to go but it worked.
Generally speaking if i have a actor and i have some functions that does a lot of calculating that i want to seperate from the actor and be able to call from the actor.
Is it ok to create a object this way that i can get the data from, instead of having it all in the same class as the actor ?

Yep that’s the correct way to initialise the UOBJECT, and yes it’s completely fine to separate stuff into a UOBJECT like that, although you may want to look into making it an ActorComponent which can be easily added to actors via blueprints etc.