LoginSignup
5

More than 5 years have passed since last update.

【UE4】C++でInterfaceを使う方法

Last updated at Posted at 2016-03-01

C++インターフェース

SampleInterface.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "SampleInterface.generated.h"


UINTERFACE(Blueprintable)
class USampleInterface : public UInterface
{
    GENERATED_UINTERFACE_BODY()
};


/**
 * サンプルインターフェース
 */
class ISampleInterface {

    GENERATED_IINTERFACE_BODY()

public: // 非const版

    UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Sample")
    void Sample();
    UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Sample")
    void SampleArg(int32 Value);
    UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Sample")
    int32 SampleResult();
    UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Sample")
    int32 SampleArgResult(int32 Value);

public: // const版
    UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Sample")
    void SampleConst() const;
    UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Sample")
    void SampleArgConst(int32 Value) const;
    UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Sample")
    int32 SampleConstResult() const;
    UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Sample")
    int32 SampleArgConstResult(int32 Value) const;

};

ブループリント側に実装

クラスの詳細->詳細パネル->インターフェースの実装を選んでください。
image

どこに実装するか

戻り値\const 非const版 const版
戻り値無し イベントグラフに実装 関数側に実装
戻り値有り 関数側に実装 関数側に実装

実装方法

  • イベントグラフ

    イベントを追加->C++で書いたイベント名を選択してください。
    image

  • 関数側
    自動的にマイブループリントの欄にインターフェースが追加されるのでそちらに実装を書いてください
    image

C++での使い方

  • インターフェースを実行
UObject* Object;

if (Object->GetClass()->ImplementsInterface(USampleCppInterface::StaticClass()))
{
    ISampleCppInterface::Execute_Sample(Object);
}
  • インターフェースを実装しているActorすべてに関数を実行
TArray<AActor*> OutActors;

// インターフェース取得
UGameplayStatics::GetAllActorsWithInterface(this->GetWorld(), USampleCppInterface::StaticClass(), OutActors);

// インターフェースを持っている対象すべての実行を行う
for (AActor* Actor : OutActors)
{
    ISampleCppInterface::Execute_Sample(Actor);
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5