I want to declare a var in C++,as like declare a var in blueprints.But I don’t know how to declare ealisy a blueprint-Objectvar in C++,just like this image.
You declare variables within the header (.h) of the class in which you want the variable to exist. Here are some examples from within different classes of my project:
/** Camera boom positioning the camera behind the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class USpringArmComponent* SpringArm;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Weapon)
TArray<TSubclassOf<class AHeroItemWeaponBase>> DefaultWeapons;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Fox Logic")
FVector CalledPosition = FVector(0.0f);
These are examples of different types of variables that can be declared within your header file. Depending on the type of variable, your code will look different. There are a few parts to declaring variables:
- UPROPERTY - A set of properties that the variable has; things such as accessibility, categories, display names, and others.
- The variable type. FVector, AActor*, custom classes, etc. It is important to include ‘class’ when defining the variable, or #include the class in question within the header file; otherwise there will be compilation issues.
- Defining a default value. Depending on the variable type, you may want to define here a default value; such as the case of the CalledPosition FVector example.
You can learn more about UPROPERTY here: Properties | Unreal Engine Documentation
Here is also a Youtube tutorial: Day 2 - UE4 c++ Variables and methods - YouTube
In cases of creating a component, after you declare the component in your header file, you will also need to create the object in the construction script. Here are some helpful links to give more information:
What is the correct way to create and add components at runtime ? - #8 by JamesMugford
I hope this helps, and good luck.