Game Engine Plugin Unreal Engine, C++
👤 Sharing: AI
```cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyCustomActor.h"
#include "Kismet/GameplayStatics.h" // Required for UGameplayStatics functions
// Sets default values
AMyCustomActor::AMyCustomActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Create a static mesh component (our visual representation)
MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));
RootComponent = MyStaticMesh; // Make it the root component
// Set some initial properties for the static mesh (can also be done in the editor)
MyStaticMesh->SetMobility(EComponentMobility::Movable); // Allow the mesh to move
MyStaticMesh->SetSimulatePhysics(false); // Don't simulate physics by default
}
// Called when the game starts or when spawned
void AMyCustomActor::BeginPlay()
{
Super::BeginPlay();
// Example usage of gameplay statics to get the player controller.
// This is for demonstration purposes and could be used to affect the player in some way.
APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0);
if (PlayerController)
{
UE_LOG(LogTemp, Warning, TEXT("Found Player Controller!"));
// Example: Disable input for the player when this actor spawns.
// Note: This is a simple example and might need more sophisticated handling
// depending on the game's input setup.
PlayerController->DisableInput(this);
// Example: Re-enable input after 5 seconds
FTimerHandle InputTimerHandle;
GetWorldTimerManager().SetTimer(InputTimerHandle, this, &AMyCustomActor::EnablePlayerInput, 5.0f, false);
}
else
{
UE_LOG(LogTemp, Error, TEXT("Could not find Player Controller!"));
}
// Example: Applying a default material
if (DefaultMaterial)
{
MyStaticMesh->SetMaterial(0, DefaultMaterial); // 0 is the material index
}
else
{
UE_LOG(LogTemp, Warning, TEXT("DefaultMaterial not set. Assign a material in the editor!"));
}
}
// Called every frame
void AMyCustomActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// Example: Rotate the mesh every frame
FRotator CurrentRotation = MyStaticMesh->GetComponentRotation();
FRotator NewRotation = CurrentRotation + FRotator(0.0f, RotationSpeed * DeltaTime, 0.0f); // Rotate around the Z-axis
MyStaticMesh->SetWorldRotation(NewRotation);
}
void AMyCustomActor::EnablePlayerInput()
{
APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0);
if (PlayerController)
{
PlayerController->EnableInput(this);
UE_LOG(LogTemp, Warning, TEXT("Player Input Re-enabled!"));
}
else
{
UE_LOG(LogTemp, Error, TEXT("Could not find Player Controller!"));
}
}
```
**Explanation:**
This code creates a simple Unreal Engine Actor (a `AMyCustomActor` class) written in C++. This Actor can be placed in your Unreal Engine level, and it will rotate and interact with the player. Here's a breakdown of the code:
**1. Header (`.h` file - not included here, but conceptually):**
The header file would declare the `AMyCustomActor` class and its members. Key declarations that *would* appear in the `.h` file (but are implied by the `.cpp` file here) include:
* `UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Custom", meta=(AllowPrivateAccess = "true"))`: The `MyStaticMesh` component, making it accessible in the editor but read-only in Blueprints.
* `UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Custom", meta=(ClampMin = "0.0", ClampMax = "360.0")) float RotationSpeed = 20.0f;`: A `RotationSpeed` variable that can be edited in the editor and accessed in Blueprints. It also includes a clamp to keep the rotation speed reasonable.
* `UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Custom") UMaterialInterface* DefaultMaterial;`: A `DefaultMaterial` variable that allows you to assign a material in the editor.
* The function declarations (prototypes) for the `BeginPlay`, `Tick`, and `EnablePlayerInput` functions.
**2. `#include` Directives:**
* `#include "MyCustomActor.h"`: Includes the header file for this class (needed for proper compilation). Unreal Engine uses a naming convention where the `.cpp` file typically includes the corresponding `.h` file.
* `#include "Kismet/GameplayStatics.h"`: Includes the `UGameplayStatics` class, which provides static functions for common gameplay-related tasks (like getting the player controller).
**3. Constructor (`AMyCustomActor::AMyCustomActor()`):**
* `PrimaryActorTick.bCanEverTick = true;`: Enables the `Tick()` function to be called every frame. Turn this off if you don't need per-frame updates to improve performance.
* `MyStaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMesh"));`: Creates a `UStaticMeshComponent`. This component will hold the actual 3D model you want to display. `TEXT("MyStaticMesh")` gives the component a name; this is important for finding and referring to the component later. `CreateDefaultSubobject` is used because it's being created during construction.
* `RootComponent = MyStaticMesh;`: Sets the `MyStaticMesh` as the root component of the Actor. The root component determines the Actor's position and rotation in the world. If you move the Actor, the root component (and therefore the static mesh) will move with it.
* `MyStaticMesh->SetMobility(EComponentMobility::Movable);`: Sets the mobility of the static mesh to `Movable`. This allows the mesh to be moved and rotated during the game. Other mobility options exist (e.g., `Static` for objects that never move).
* `MyStaticMesh->SetSimulatePhysics(false);`: Disables physics simulation for the mesh. If you wanted the mesh to be affected by gravity and collisions, you would set this to `true`.
**4. `BeginPlay()` Function:**
* `Super::BeginPlay();`: Calls the `BeginPlay()` function of the parent class (in this case, `AActor`). This is crucial to ensure that the parent class performs its initialization. Always call this first.
* `APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0);`: Gets the player controller for the first player (index 0). The player controller handles player input.
* `if (PlayerController)`: Checks if a valid player controller was found.
* `PlayerController->DisableInput(this);`: Disables input for the player, which means the player can no longer use their keyboard, mouse, or gamepad to control the game. `this` specifies that the disabling of input is specific to this actor. The actor will need to re-enable input before the player can use the input.
* `FTimerHandle InputTimerHandle;`: Creates a `FTimerHandle` to store the timer's identifier.
* `GetWorldTimerManager().SetTimer(InputTimerHandle, this, &AMyCustomActor::EnablePlayerInput, 5.0f, false);`: Sets a timer to call the `EnablePlayerInput()` function after 5 seconds. This demonstrates how to delay an action in Unreal Engine. `false` means the timer only executes once.
* `else`: Logs an error message if the player controller was not found. This is important for debugging.
* Material Assignment:
* `if (DefaultMaterial)`: Checks if a `DefaultMaterial` has been assigned in the editor.
* `MyStaticMesh->SetMaterial(0, DefaultMaterial);`: Assigns the `DefaultMaterial` to the static mesh. `0` specifies the material index. A mesh can have multiple materials assigned to different parts of it. You'd set different indices to change different materials on the mesh.
* `else`: Logs a warning if no material has been assigned.
**5. `Tick()` Function:**
* `Super::Tick(DeltaTime);`: Calls the `Tick()` function of the parent class. Again, this is essential.
* `FRotator CurrentRotation = MyStaticMesh->GetComponentRotation();`: Gets the current rotation of the static mesh component.
* `FRotator NewRotation = CurrentRotation + FRotator(0.0f, RotationSpeed * DeltaTime, 0.0f);`: Creates a new rotation by adding a rotation around the Z-axis to the current rotation. `DeltaTime` is the time in seconds since the last frame. Multiplying `RotationSpeed` by `DeltaTime` ensures that the rotation speed is consistent regardless of the frame rate.
* `MyStaticMesh->SetWorldRotation(NewRotation);`: Sets the new rotation of the static mesh.
**6. `EnablePlayerInput()` Function:**
* `APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0);`: Gets the player controller, just as in `BeginPlay`.
* `if (PlayerController)`: Checks if the player controller is valid.
* `PlayerController->EnableInput(this);`: Enables input for the player, allowing them to control the game again.
* `UE_LOG(LogTemp, Warning, TEXT("Player Input Re-enabled!"));`: Logs a message to the console confirming that player input has been re-enabled.
* `else`: Logs an error message if the player controller couldn't be found.
**How to Use This Code in Unreal Engine:**
1. **Create a New C++ Class:** In the Unreal Editor, create a new C++ class that inherits from `Actor`. Name it `MyCustomActor`. Unreal Engine will automatically generate the `.h` and `.cpp` files.
2. **Replace the Code:** Replace the contents of `MyCustomActor.cpp` with the code above.
3. **Compile:** Compile the code in Unreal Engine (Build -> Build Solution).
4. **Add to Level:** Drag an instance of the `MyCustomActor` from the Content Browser into your level.
5. **Assign a Static Mesh:** Select the `MyCustomActor` in the level. In the Details panel, find the `My Static Mesh` section (it'll be under a category you specified in your `.h` file, typically "Default"). Assign a Static Mesh asset from your project to the `Static Mesh` field. If you don't have one, import a `.FBX` file or use one of the starter content meshes.
6. **Set Rotation Speed (Optional):** In the Details panel, change the `Rotation Speed` variable to control how fast the mesh rotates.
7. **Assign Material (Optional):** In the Details panel, change the `Default Material` variable to control the material of the mesh. You'll need to create a material asset in the Content Browser first (Right Click -> New -> Material).
8. **Play:** Run the game. You should see the static mesh rotating. Also, for the first 5 seconds the player input will be disabled and then re-enabled. You can verify this by trying to move your character right after the game starts and then again after 5 seconds. You will be able to move your character only after 5 seconds.
**Key Unreal Engine Concepts Demonstrated:**
* **Actors:** The fundamental building blocks of Unreal Engine levels.
* **Components:** Reusable pieces of functionality that can be attached to Actors (like `UStaticMeshComponent`).
* **Properties (`UPROPERTY`):** Variables that are exposed to the editor and/or Blueprint scripting. The `UPROPERTY` macro controls how the variable is exposed and what features it has.
* **`BeginPlay()`:** Called when the Actor is spawned into the world.
* **`Tick()`:** Called every frame, allowing you to update the Actor's state.
* **`DeltaTime`:** The time elapsed since the last frame, used for frame-rate-independent calculations.
* **`UGameplayStatics`:** A utility class with static functions for common gameplay tasks.
* **Timers:** Used to execute code after a delay.
* **Logging (`UE_LOG`):** Used for printing messages to the Unreal Engine Output Log, which is helpful for debugging.
This example provides a foundation for creating more complex Actors in Unreal Engine using C++. You can expand on this by adding more components, properties, and functionality. Remember to always refer to the Unreal Engine documentation for detailed information on the available classes and functions.
👁️ Viewed: 7
Comments