Accessing properties of TSubclassOf

Hi, I’m new to programming and I am really struggling with TSubclassOf.
I have a main C++ class called Gun and whenever I need to add a new gun I just create a blueprint child of said class and then add the mesh and everything in the blueprint. But now when I want to use the gun with my character, the only way I can get it to work is through using TSubclassOf. And I know it’s probably really simple but I can’t seem to figure out how to access the properties of these guns after I have set them in the blueprint of my player class (Which is a child of a C++ player class).

Here is how I set the properties in the C++ player:

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Weapons")
	TSubclassOf<AGun> Sidearm;

But now how do I access the property Icon for example in C++ or blueprints or anything?

PS. If you need anymore context or information lmk

How do you use that Sidearm class in code for example, you must be using that class to spawn the gun, spawning gives you a reference to the spawned gun, once spawned you can access its properties and change them if needed.

Example

if(AGun* SpawnedGun = GetWorld()->SpawnActor<AGun>(Sidearm, FTransform()))
{
	//Access ammo or whatever properties
	SpawnedGun->Ammo = 30;
}
1 Like

You should be able to access the property both in Blueprints and in C++. The property is just the type of actor class you are going to use not the actual spawned instance.

To use the gun you will need to spawn an instance of it, and put that instance into a property (variable) so it doesn’t get garbage collected.

I don’t remember exactly what the functions are called in C++ or Blueprints, it’s something along the lines of SpawnActor.

So just to clarify, in your code you could use the SpawnedGun variable whenever you want as long as its been spawned in? You can use it just like any other variable despite me setting it to a SubclassOf in the header file?

The TSubclass is just a way for you to indicate a certain actor class, in my example you can see we used it in the SpawnActor function, so we used that function and passed in the gun class we want to spawn.

Typically you would use spawn the gun save it into a variable and use that variable in your code.

Here’s a typical setup:
In your header we have the gun class, we will use this class to determine what gun to spawn, in BP you can change it to whatever class deriving from AGun.

The gun does not exist yet so we need to have a variable to store it somewhere, this way we can access that gun during gameplay/

Let’s say for example you spawn the gun in begin play and attach it like this

Anywhere in your character you can use the spawned gun pointer to use and access the gun’s variables and function.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.