How can I spawn an actor from an array / create a character loading system using C++?

Hi

So I created a CPP class called ANEPSideScroller and this class handles all my game logic for the playable characters. I then created a BP class from this and duplicated it 3 times. Each of these blueprints now contain a different skeletal mesh, power/speed/etc stats, poster images, attack combos etc thus giving me 4 unique playable characters from one shared class

Next I created a variable of type TArray<TSubclassOf < ANEPSideScroller > > in my GameInstance and configured the array to hold a reference to the 4 character blueprints.

So far so good… but now comes the problem. I want to actually SPAWN these characters when the player clicks on “Start level”. First they click on a widget to select a player which simply sets an index int32 in the game instance.

I want to do this in C++ but all I can find is a function called SpawnActor that takes a class as a parameter, not an object. I believe in Blueprint there is a SpawnActorOfClass and a SpawnActorOfObject so in BP this should be easy enough but I am trying to do this in C++ and simply don’t know what to do…

I can’t use SpawnActor() because all 4 characters have the same class but there doesn’t seem to be a way to spawn an actor based on a reference so what do I do?

The only solution I can come up with, since I made an array of TSubClassOf, is to generate a new class for each character, even though I won’t be doing anything in any of them. They simply need to exist for the sole purpose of existing and nothing more and then I can spawn my characters using a switch… but still… I won’t be able to spawn them from the SelectableCharacters array unless I make a TArray< UClass > variable instead…

What do I do?
Thanks in advance
C++ CPP Player-Character spawning-actors

I seem to have found the answer…

The solution lay in using soft references rather than hard references…!

	UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Character Select")
	TArray<TSoftClassPtr<ANEPSideScroller>> SelectableCharacters;

Then make use of it like so…

	UFUNCTION(BlueprintCallable)
	void SpawnPlayerCharacter(uint8 PlayerIndex)
	{
		int32 CharacterIndex = SelectedPlayableCharacters[PlayerIndex];
		if (SelectableCharacters[CharacterIndex].IsPending())
		{
			const FSoftObjectPath& AssetRef = SelectableCharacters[CharacterIndex].ToSoftObjectPath();
			SelectableCharacters[CharacterIndex] = Streamable.LoadSynchronous(AssetRef);
		}
		ANEPSideScroller* Character = Cast<ANEPSideScroller>(SelectableCharacters[CharacterIndex].Get());
	}
1 Like

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