Spawn Actor/Object from code

Hi!

I switched from Unity3D to UE4 and I have the following problem:

In Unity3D I created prefab with some objects inside. And in other script I Instantiated the prefab into world.
In UE4 I created blueprint, because here I can build objects together using visual editor, but I have my game code in C++, so I need to spawn the blueprint from C++ (and interact with it in C++).

Is there any way how to this?
I read the Blueprint will be available only from editor, so is there any other solution?
Thanks.

"Is there any way how to this? I read the Blueprint will be available only from editor, so is there any other solution? "

You absolutely can interact with Blueprints from c++ !

I do it all day!

To answer your question, yes you can spawn Blueprint Actors with all your custom setups straight in the C++.

To answer all your other unasked questions:

You can do anything in c++! UE4 C++ is amazingly powerful!

Rama

Thank you, can you please write a little example how to do this please?

And can you make separate actors via Construction Scripts using c++?
This question arises every time
https://answers.unrealengine.com/questions/60041/videobphow-to-make-separate-blueprints-via-constru.html
Similar unsolved problem to Rama specially

Here is how I spawn a blueprint via C++. Note that the blueprint I spawn has a base class that was created in C++ also.

.h

 TSubclassOf<YourClass> BlueprintVar; // YourClass is the base class that your blueprint uses

.cpp

 ClassThatWillSpawnTheBlueprint::ClassThatWillSpawnTheBlueprint(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP)
 {
      static ConstructorHelpers::FObjectFinder<UBlueprint> PutNameHere(TEXT("Blueprint'/Path/To/Your/Blueprint/BP.BP'"));
      if (PutNameHere.Object) {
           BlueprintVar = (UClass*)PutNameHere.Object->GeneratedClass;
      }
 }

PutNameHere is just an arbitrary name you give to the constructor helper. The path to your blueprint is found by finding your blueprint in the content browser, right clicking it, and choosing Copy Reference. Then, just paste that in between the quotes.

Now, youā€™re ready to spawn the blueprint. You can do it in BeginPlay() or wherever, just not in the constructor.

 UWorld* const World = GetWorld(); // get a reference to the world
 if (World) { 
      // if world exists
      YourClass* YC = World->SpawnActor<YourClass>(BlueprintVar, SpawnLocation, SpawnRotation);
 }

If you donā€™t know your SpawnLocation or SpawnRotation you can just throw in FVector(0,0,0) and FRotator(0,0,0) instead.

So, since your blueprint base class was also created in C++ this makes it easy to interact with your blueprint from code. Itā€™s as simple as YC->SomeVariable = SomeValue. Hope that helps.


EDIT: A more in depth explanation how this works.

Summary

Communicating with a blueprint via C++ requires some initial setup with the blueprint you need to communicate with. It is not possible to talk to a blueprint variable that was created inside of blueprints via C++. It has to be a C++ variable that the blueprint simply uses. You do this by creating your own base class in C++ for the blueprint, declaring all of the variables that your blueprint will need inside that class, and then setting the parent class of your blueprint to your base C++ class.

Creating the base class

First, you need to create a base class for your blueprint, probably extending from AActor. Then declare your variables in the .h like so:

UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = Projectile)
float ProjectileSpeed;  // just an example

Only UPROPERTY variables will work. BlueprintReadWrite means this variable can both be read and written to inside of blueprints. EditDefaultsOnly is optional but it will allow you to edit that variable within the blueprint defaults if you need to. For example, you could tweak the speed without having to recompile everything.

Parenting the blueprint

Once you have your base class written and compiled, you will need to parent your blueprint to that class.

  1. open blueprint
  2. click graph
  3. click blueprint properties
  4. in the details panel, scroll down until you see Parent Class and use the drop down to choose your C++ class.

You can also set the base class at the time of blueprint creation. As long as your class is compiled it will show up as an option.

Accessing inherited variables inside of blueprints

You will now be able to access the variables you created in your C++ class from inside your blueprint by clicking the ā€œshow inherited variablesā€ tick box. Since we set the category to ā€œProjectileā€ above, that is where they will be listed. And since we made them BlueprintReadWrite, we can use them.

You will have to replace any variables youā€™ve already created in the blueprint with these new inherited variables from the base class. For example if you had created a variable in blueprints called ProjectileSpeed and used that in 5 different places, you would have to remove all of them, delete that variable and replace them with the inherited ProjectileSpeed instead. This can get confusing and is a pain, especially if your graph is big. To make this easier you could call the inherited variable something different like ParentProjectileSpeed or something, that way neither you or the editor will get confused about which is which.

Spawning the blueprint via code and communicating with it

After this is done, you can then spawn and communicate with this blueprint via C++. If your base class is called AMyProjectile then you would write:

void AClassThatWillSpawnTheBlueprint::BeginPlay()
{
	UWorld* const World = GetWorld(); // get a reference to the world
	if (World) {
		// if world exists

		// we are now creating a new instance of this blueprint
		AMyProjectile* Missile = World->SpawnActor<AMyProjectile>(BlueprintVar, SpawnLocation, SpawnRotation);
	}

	// setting a blueprint instance's variable
	Missile->ProjectileSpeed = 100;
}

Keep in mind your BlueprintVar will need to use this base class as well.

TSubclassOf<AMyProjectile> BlueprintVar;
3 Likes

I am also switching from Unity3D and need help understanding the different paradigms, could I contact you somehow for help?

As I cannot create a topic, I will answer here hoping that someone might give it a read.

Spawning a Blueprint in c++ with 4.7 error C2027: use of undefined type ā€˜UBlueprintā€™

Just trying to spawn a Blueprint Projectile instead of the c++ class projectile within the Twin Stick Shooter Template.

Read through all the other topics and tried to do it like it has been described here: Spawn Actor/Object from code - C++ - Unreal Engine Forums

Sadly, I just cannot seem to get it to work, even after many hours of trying out different things. Given that I am very new to c++ and used to Java, I might be lacking the proper skills, but I still would love to know where I made a mistake in this simple process. here is a screenshot of the errorlog and code: Dropbox - Error

Any help would be greatly appreciated as I just cannot get around the Ublueprint error.

Thanks so much!

Add #include "Engine/Blueprint.h" to the list of includes at the top of your cpp file.

Thank you for your quick reply! I thought there had to be an include for that. sadly, #include ā€œBlueā€¦ā€ searching and google searches on that did not point me to that one.

Now the Compiler shows me a bunch of new errors in all 3 files (2 of which i didnt touch at all). http://i.imgur.com/56pFSpg.png

Any more help would be even more greatly appreciated! Sorry for being a newb.

What engine version are you using? I didnā€™t have to include Engine/Blueprint.h for it to work, but I was using 4.5.1. Maybe something changed.

Using 4.7, new to C++ and rather new to UE4. Watching the C++ tutorials from Epic did not really prepare me for the 3 hours of trying to get a super simple thing to work sadly. :confused:

Can you show me the full code of that class?

Pack it into http://pastebin.com/ and post the link here please.

PS: If i donā€™t answer right away, itā€™s due to 01:44 oā€™clock in germany and i need some sleep :smiley:

EDIT: Okay, after some more time I got it to work by creating a new project with the template and just adding new code line by line and compiling after every line. What caused the old code you see below to crash was most likely the spawn call. it needed to be

World->SpawnActor < AActor >
(I needed to put the spaces because otherwise the text wouldnt wanna show up in the comment)
Now I have the next problem. I have no idea how I should set all the variables I need to set on spawn (because I have no idea how to tell the c++ code about which variables the blueprint class has and needs) and I slowly get the impression that itā€™s just a bad idea to wanna access such a blueprint within c++ code?

Old Post:
01:52, Germany here as well :wink: Thanks for your help. Here are the classes:
h: TwinStickCPawn.h - Pastebin.com
cpp: TwinStickCPawn.cpp - Pastebin.com

Note that I tried using
TSubclassOf BlueprintVar;
and
UClass* BlueprintVar;
in the h file, neither worked.

Thanks so much for trying to help everyone!

I noticed one problem in the files. Your BlueprintVar is not being set at line 35 in the .cpp. It should be:

BlueprintVar = (UClass*)ASD.Object->GeneratedClass;

Also, in the .h you shouldnā€™t need to specify the class keyword:

TSubclassOf<class AActor> BlueprintVar;

Do it like this instead:

TSubclassOf<AActor> BlueprintVar;

Iā€™m not sure if that will make any difference but thatā€™s how Iā€™ve done it.

Also, you should not be using AActor, but rather your own class that extends AActor, because you wonā€™t be able to declare the variables you need for your blueprint inside of AActor. Iā€™m working on a more in depth explanation how this all works. Iā€™ll update my original answer when itā€™s done.

Iā€™ve updated my answer and hopefully it will help you a bit more. If you have any other questions let me know.

Thank you very much for taking the time to write such an indepth answer about this topic Sir Kochab. I think it helped me greatly understanding the concept and possible connections between c++ classes and blueprints and I will spend the next hours trying to put that new knowledge to good use!

Give that man Upvotes!

Iā€™m the 3rd person here moving from Unity to Unreal; hit me up if yā€™all wanna chat.