Checking if a class implements a UInterface

Follow the first two recipes so that you have a UInterface we can check for, and a class implementing the interface, which can be tested against.

How to do it...

  1. Inside your Game Mode implementation, add the following code to the BeginPlay function:
    FTransformSpawnLocation;
    ASingleInterfaceActor* SpawnedActor = GetWorld()->SpawnActor<ASingleInterfaceActor> (ASingleInterfaceActor::StaticClass(), SpawnLocation);
    if (SpawnedActor->GetClass()->ImplementsInterface(UMyInterface::StaticClass()))
    {
      GEngine->AddOnScreenDebugMessage(-1, 1, FColor::Red, TEXT("Spawned actor implements interface!"));
    }
  2. Given that we are referencing both ASingleInterfaceActor and IMyInterface, we need to #include both MyInterface.h and SingleInterfaceActor.h in our Source file.

How it works...

  1. Inside BeginPlay, we create an empty FTransform function, which has the default value of 0 for all translation and rotation components, so we don't need to explicitly set any of them.
  2. We then use the SpawnActor function from UWorld so that we can create an instance of our SingleActorInterface, storing the pointer to the instance into a temporary variable.
  3. We then use GetClass() on our instance to get a reference to its associated UClass. We need a reference to UClass, because that object is the one which holds all of the reflection data for the object.
  4. Reflection data includes the names and types of all UPROPERTY on the object, the inheritance hierarchy for the object, and a list of all the interfaces that it implements.
  5. As a result, we can call ImplementsInterface() on UClass, and it will return true if the object implements the UInterface in question.
  6. If the object implements the interface, and therefore, returns true from ImplementsInterface, we then print a message to the screen.

See also

  • Chapter 5, Handling Events and Delegates, has a number of recipes relating to the spawning of actors
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.46.18