使用UE4開發FPS游戲將近1年半的時間了.伴隨着對於UE4的越來越深入的理解.以前的編程觀念發生了很大的改變.寫下來做一個記錄
1,為Actor添加功能還是創建Component封裝功能
最近在編寫一個體感控制功能,根據運動控制器的方向來確定角色的移動方向.是否跳躍等.在開始使用UE4時,我會把功能放在Character類中,漸漸的Character類的功能越來越多,維護起來也變得復雜了.而且Character類在諸多文件中都要包含,每次改變Character類的聲明,都需要重現編譯很多文件,開發效率變低.當創建Component來封裝體感控制功能時,代碼變得內聚,Character類只需要掛接此Componnent,就可以提供功能.在開發此組件時,每次編譯只要編譯此Component即可,極大的加快了編譯速度.所以使用Component來開發功能優勢很明顯.
2,使用BlueprintCallable,BlueprintImplementableEvent函數在藍圖中調試
為一個函數加上BlueprintCallable可以在藍圖中方便調用,而為一個函數加上BlueprintImplementableEvent,則可以在藍圖中實現,然后打印變量,或者繪制調試圖形,調用DebugDrawLine系列函數.
3,添加UBlueprintFunctionLibrary函數
UBlueprintFunctionLibrary中的函數可以在藍圖中全局調用,把常用的功能寫入它里面,可以提高開發效率.例如下面使用meta = (WorldContext = "WorldContextObject")標記可以在藍圖中把當前上下文對象傳入
UCLASS() class SHOOTERGAME_API UShooterBlueprintFunctionLibrary : public UBlueprintFunctionLibrary { //獲取其他的玩家 UFUNCTION(BlueprintPure, meta = (WorldContext = "WorldContextObject"), Category = "Player") static AShooterCharacter* GetOtherPlayer(UObject* WorldContextObject, AShooterCharacter* Player); } AShooterCharacter* UShooterBlueprintFunctionLibrary::GetOtherPlayer(UObject* WorldContextObject, AShooterCharacter* Player) { if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject)) { for (TActorIterator<AShooterCharacter> it(World); it; ++it) { if (*it != Player) { return *it; } } } return nullptr;
4,UPROPERTY屬性標記
虛幻的垃圾回收依賴於UPROPERTY,不管是在struct,還是在class中,對於UObject及其子類類型的屬性,都需標記UPROPERTY,以防止被垃圾回收.
5,Replicated屬性
Replicated屬性用於同步服務器的狀態到客戶端中,尤其對於中途加入的玩家,標記為Replicated的屬性可以保持客戶端與服務器端的狀態一致
