Skip to main content
 首页 » 资源教程 » UE4教程

【UE4官方文档翻译】Unreal Engine 4 For Unity Developers (针对Unity开发者的UE4)

2016年09月09日 22:23:312989040



Unreal Engine 4 For unity



This guide provides an overview of UE4 from the viewpoint of a Unity user, and aims to help you translate your existing Unity experience into the world of UE4.

The Editor (编辑器)

Below are pictures of the Unity Editor and Unreal Editor, color-coded to indicate common functionality. Each block is labeled to show the equivalent UE4 terminology. Unreal Editor's layout is fully customizable by dragging and dropping tabs around.


Editing Assets (编辑资源)

In Unity, the Inspector tab is used to edit selected assets in your Project. In UE4, the Details panel exposes properties of selected objects, while larger editing tasks lead to a dedicated window or tab. New tabbed windows will open for each edited asset, similar to a web browser. Of course, you can freely drag the tabs around or float them as standalone windows.


Quick Glossary (术语快览)

The following section contains common Unity terms on the left and their UE4 equivalents (or rough equivalent) on the right. UE4 keywords link directly to more in-depth information inside Unreal Engine's Online Documentation.

Category Unity UE4
Gameplay Types Component Component
  GameObject ActorPawn
  Prefab Blueprint Class
Editor UI Hierarchy Panel World Outliner
  Inspector Details Panel
  Project Browser Content Browser
  Scene View Viewport
Meshes Mesh Static Mesh
  Skinned Mesh Skeletal Mesh
Materials Shader MaterialMaterial Editor
  Material Material Instance
Effects Particle Effect Effect, Particle, Cascade
  Shuriken Cascade
Game UI UI UMG (Unreal Motion Graphics)
Animation Animation Skeletal Animation System
  Mecanim Persona , Animation Blueprint
2D Sprite Editor Paper2D
Programming C# C++
  Script Blueprint
Physics Raycast Line Trace, Shape Trace
  Rigid Body Collision, Physics
Runtime Platforms iOS Player, Web Player Platforms

Projects and files (项目与文件)

So what are all these directories and files? (这些目录和文件是什么?)

Just like Unity projects, Unreal projects always exist in their own directory and have their own project file. You can double-click on.uproject files to load your game into the Unreal Editor, or right-click for additional options. Project folders have various sub-folders that contain your game's content and source as well as various configuration files and binaries. The most important are the Content andSource sub-folders.
就像Unity项目,Unreal项目总是存在于它们自己的目录下,并有者自己的项目文件。你可以双击或右键点击.uproject 文件来加载你的游戏到虚幻编辑器中。项目文件夹下又有许多子文件夹,它们包含了你的游戏内容和资源,以及各种配置文件和二进制文件。其中最重要的是Content和 Source子文件夹。

Where do I put my assets?(我应该把资源放在哪里?)

In UE4, each project has a Content folder. Similar to a Unity project's Assets folder, this is where your game assets are stored. To import assets into your game, simply drop files into your project's Content directory and they will be automatically imported and appear in theContent Browser. The assets in the editor will update automatically as you make changes to the files using an external program.
与Unity的Assets文件夹类似,在UE4中,每个项目都有一个Content文件夹用来存放资源。为了导入资源到游戏中,你可以直接将文件拖到你项目的Content目录下,它们会自动被导入并显示在Content Browser中。当编辑器中的资源文件会在发现改编后自动更新。

image alt text

What common file formats are supported?(支持哪些文件格式?)

Unity supports a wide array of file formats. UE4 supports the most common file types:

Asset Type Supported Formats
3D .fbx, .obj
Texture .png, .jpeg, .bmp ,.tga, .dds, .exr, .psd, .hdr
Sound .wav
Fonts .ttf, .otf
Videos .mov, .mp4, .wmv

How is my Scene stored?(场景如何存储?)

In Unity, you place GameObjects in a scene and save that as a Scene asset file. Unreal has a Map file that is similar to a Unity Scene. Map files store data about your Level and the objects in it, as well as lighting data and certain level-specific settings.

How do I change my project's settings?(如何更改项目设置?)

All project settings can be found from the main menu under Edit / Project Settings. Like Unity's project settings, these allow you to specify information about your project (such as project name and icons), configure game input bindings, and define how the engine behaves when running your project. You can learn more about individual project settings here. Unity also has what is called "player settings". In Unreal, these are "platform settings", and can be found under the "Platforms" category in your project settings.
UE4的所有项目设置可以在主菜单下的Edit / Project Settings中找到,就像可以在Unity的project settings修改你的项目信息(比如项目名和图标),配置游戏输入绑定,以及定义项目运行时的引擎行为  一样 。你可以在这里获取更多关于project settings的信息。

Where do my source files go?(源文件应该放在哪里?)

In Unity, you are accustomed to placing C# source files in your assets folder.

UE4 works differently. For projects that have C++ code, you will find a "Source" sub-folder under the project directory that has various files, including C++ source (.cpp) and header (.h) files, as well as some build scripts (.Build.cs, .Target.cs) However, Blueprint-only projects will not have a Source folder.
但UE4却不是这样的。对于C++创建的项目,你会在项目目录下找到"Source"子文件夹,它包含了.cpp 和 .h文件,还有一些编译脚本(.Build.cs, .Target.cs)。而通过蓝图创建项目的就没有Source这个文件夹。

The easiest way to get started with C++ in UE4 is to use the editor to Add Code to Project (in the main File menu), or to simply create a new C++ project from scratch from one of the many templates. You can find C++ classes right in the Content Browser and can open the files in Visual Studio or Xcode by double-clicking on their icons.
UE4开始C++项目的最简单方法就是通过(主菜单下)Add Code to Project指令 ,或则选择C++模板新建项目。你可以在Content Browser中找到C++类,并使VS或者Xcode双击打开。

From GameObjects to Actors (从 GameObjects 到 Actors)

Where Is My GameObject?(GameObject呢?)

In Unity, a GameObject is a "thing" that can be placed in the world. The UE4 equivalent is an Actor. In the Unreal Editor, you can drag a new Empty Actor into the viewport from the Placement panel:
Unity中的GameObject是可以被放到世界里的东东。UE的Actor与之等效。在Unreal编辑器中,你可以直接从Placement面板中拖动Empty Actor到 viewport(世界)中。

image alt text

You could build a game out of Empty Actors, but UE4 also includes special types of Actors with built-in features, such as a Pawn (for players or AI objects), or Character (for animated creatures.) Just like Empty Actors, you can drop these special types of Actors down, then add or customize their properties and components. You will learn more about it later, but for now try to remember that UE4 has a Gameplay Framework that works with these special Actors.
你可以使用Empty Actor来创建一个游戏,但是UE4也内置了其他如  Pawn(用于玩家或AI对象) \ Character(用于可动生物) 一样特定类型的Actor. 就像Empty Actor一样,你可以将这些特定类型的Actor拖进场景中,然后为其添加或定制它们的属性和组件。稍后我们将学习与它相关的更多内容,但现在尽量去记住UE4有一个与这些特定Actor相关联的 Gameplay Framework 。

Actors in UE4 are a bit different than GameObjects in Unity. In Unity, GameObject is C# class which you cannot directly extend. In UE4, Actor is a C++ class which you can extend and customize using inheritance. We will talk about this more later on!
UE4的Actor和UnityDe GameObject有点不同的是:Unity中的GameObject是不可扩展的C#类,而UE4的Actors是可通过继承的方式扩展并自定义的C++类。我们将在之后扩展讨论它。

Where Are My Components?(组件呢?)

In Unity, you add components to a GameObject to give it functionality.

In UE4, you add components to Actors. After you have dropped an Empty Actor in your level, click the Add Component button (in theDetails panel) and choose a component to add. Here, we are creating a torch by dropping an empty Actor, then adding a mesh component for the base, followed by a light source and then a particle system to create its flame.
在UE4,你添加组件给Actor.当你在关卡中放置一个Actor之后,点击ADD Component(在Detail面板中) 选择一个组件进行添加。这里,我们通过放置的Empty Actor创建一个火炬,然后添加mesh组件为其基础,再之后为其添加一个光源,最后再添加一个粒子系统来创建火焰。

image alt text

In Unity, a GameObject hold a flat list of components, but in UE4 an Actor actually contains a hierarchy of components attached to one another. You can see this in the example above, where the Light and Particle are attached to the Mesh. This has some important implications discussed later in Complex Actors and GameObjects.
在Unity中,GameObject的所有组件是处于一个平面列表中的,而在UE4中,Actor的组件可以存在层级关系。如上面的例子,Light 和 Particle 依附在了mesh上。这会有一些重要的意义,我们将在在之后的Complex Actors and GameObjects章节中讨论。

From Unity prefabs to UE4 Blueprint Classes(从 Unity 的 prefabs 到 UE4 的 Blueprint Classes)

Unity's workflow is based on prefabs. In Unity you build a set of GameObjects with components, then create a prefab from them. You can then place instances of the prefab in your world, or instantiate them at runtime.

UE4's corresponding workflow is based on Blueprint Classes. In UE4, you build an Actor with components, select it, and click the "Blueprint / Add Script" button (in the Details panel). Then, choose a place to save your Blueprint Class, and click "Create Blueprint" to save your new Blueprint Class!
UE4相应的工作流是给予Buleprint Classes的。在UE4中,你创建了一个带有组件的Actor,选中后点击 Details面板中的"Blueprint / Add Script。然后,找个位置来存放你的的Blueprint Classes,最后点击"Create Blueprint保存。

image alt text

Your new Blueprint Classes can be found in the Content Browser. You can double-click to edit them directly, or you can drag and drop them into any level.
Content Browser可以找到你的Blueprint Classes。你可以直接双击编辑它们,或者你可以将其拖进任何关卡中。

Where is Script Component and MonoBehaviour?(脚本组件和 MonoBehaviour呢?)

In Unity, you have Script Components that you drop on GameObjects to add C# scripting. You create a class that inherits from MonoBehaviour to define what that component does.

UE4 has something similar. You can create whole new Component classes of your own and drop those onto any Actor. You can create Component classes using either Blueprint Scripting or C++.

So how do you create your own component class in UE4? In the Details panel's Add Component drop-down, you see you can create new components, or choose existing ones:
那么,如何在UE4中创建自己的组件类呢。在Details片板中的Add Component 下拉选项中,比可以看到创建系组建或选择已有组件。

image alt text

In Unity, when creating a new MonoBehaviour, you will be given a skeleton class file with a Start() function and an Update() function.

In UE4, you will also be given a skeleton class with a InitializeComponent() function and a TickComponent() function, which perform functions similar to Start and Update.
在UE4,你也会得到带有 InitializeComponent()   TickComponent()  方法的类,它们的功能与Start()和Update类似。

If you create a Blueprint Script Component you will be given these same functions as visual nodes:

image alt text

Scriptable Actor Blueprint Classes(可编辑的Actor蓝图)

Here is a cool feature in UE4: Your new Actor Blueprint Class can have its own Blueprint Visual Scripting! This allows you to add logic to an entire object, not only an individual component. Combined with inheritance (explained below), this gives you a lot of flexibility when designing your game.

In addition to Blueprint Classes supporting visual scripting, UE4 also supports C++ Classes implemented with code. Here are both, side-by-side.

Unity C# UE4 C++
using UnityEngine;
using System.Collections;

public class MyComponent : MonoBehaviour
    int Count;

    // Use this for initialization.
    void Start ()
        Count = 0;

    // Update is called once per frame.
    void Update () 

        Count = Count + 1;
#pragma once
#include "GameFramework/Actor.h"
#include "MyActor.generated.h"

class AMyActor : public AActor
    int Count;

    // Sets default values for this actor's properties.
        // Allows Tick() to be called
        PrimaryActorTick.bCanEverTick = true;  

    // Called when the game starts or when spawned.
    void BeginPlay()
        Count = 0;

    // Called every frame.
    void Tick(float DeltaSeconds)
        Count = Count + 1;
UE4 Blueprint

UE4 Blueprint Classes can be extended (UE4的蓝图可被扩展)

Unity prefabs and UE4 Blueprint Classes can be instantiated in your game similarly. However, Unity has complications related to nesting prefabs within other prefabs, which limit their role as extensible building blocks.
Unity的prefabs和UE4的 Blueprint Classes 可以在你的游戏中相似的被实例化出来。然而,Unity会有prefabs嵌套prebabs的并发机制,这种机制限制了它们作为可扩展块的功能。

In UE4, you can create a new Blueprint Class which extends an existing Blueprint Class and augments it with new properties, components, and visual scripting functionality.
在UE4,你可以穿件新的Blueprint Class,来扩展已存在的蓝图类,并通过新的属性、组件可可视化脚脚本方法来增强它。

For example, in UE4 you can create a Blueprint Class named Monster which implements basic monster functionality such as chasing people. You can then create further Blueprint Classes which extend it, such as Dragon (a type of Monster which adds fire-breathing features), Grue (a Monster which is likely to eat you when it is dark), and for example 8 others. These subclasses of Monster all inherit the basic functionality from Monster, and add new capabilities on top.

In Unity, you would implement this by creating many different GameObject prefabs: one for Dragon, one for Grue, and so on. Now, say you want to add some new functionality to all monsters, such as the ability to speak using your new Speak Component. In Unity, you have to go and update all 10 prefabs to individually copy and paste the new functionality into it.
在Unity ,你可以通过创建不同的GameObject预设来实现这样的功能:Dragon预设、Grue预设、等等。现在,你想为所有的怪兽添加新的功能,比如使用你的Speak组件来使它们说人话。在Unity中,你需要对这10个预设一个一个地更新,来为它们添加新的功能。

In UE4, you can simply modify the Monster Blueprint Class to add this new ability to speak. That's all! Dragon, Grue, and the 8 other subclasses of Monster automatically inherit the new speaking functionality, and you do not need to touch them.

But there is more! Everything we have said here about Blueprint Classes also applies to C++ Classes, and everything is equally true of Actors and Components. These systems are designed to support large-scale development of extensible functionality, and can scale to projects with 10's or 100's of developers.
更值得一提的是,我们所说的关于Blueprint Classes的一切同样适用于C++ Classes ,适用于Actor和Component。这种系统是为大规模可扩展功能的开发而设计的,并可扩展到10到100人的项目当中去。

Should I use Blueprint Scripting, C++, or both? (我该使用蓝图、C++,还是都使用?)

Blueprint Visual Scripting is ideal for simple in-game logic flow and sequencing of actions. It is a great system for designers, artists, and visually-oriented programmers, because it is easy to access and control in-game objects visually. You can even create small standalone-game using just Blueprints; see the Tappy Chicken sample for a full-fledged example.
蓝图的可视化编程是针对于简单的游戏逻辑流和动作顺序的。它对设计者、艺术家和视觉导向的程序员来说,是一种友好的系统,以为它可以通过可视化的方式来控制游戏对象。你甚至可以只用蓝图就开发独立游戏;可以参考Tappy Chicken案例。

C++ programming is for larger-scale tasks, such as building gameplay systems, complex AI, and new engine features. If you already have some C++ experience, check out the Introduction to C++ Programming in UE4 page.
C++编程用来处理大规模任务,比如创建游戏系统、复杂AI和新的引擎特性。如果你有点C++经验,参考一下 Introduction to C++ Programming in UE4 。

Most projects will use a mix of Blueprints and C++. Many developers prototype game functionality using Blueprints, because it is so easy and fun, and later move some or all of it to C++ for performance and engineering rigor.

Blueprint Classes can extend C++ Classes (蓝图可以扩展C++类)

Much of the magic of UE4 game development comes from the interplay between programmers implementing new features in C++, with designers and artists utilizing them in Blueprints and then asking for more! Here's how a team might structure a UE4-based shooter game implementing pickups using a mix of C++ Classes systems programming, and Blueprint Classes for behavior and appearance:

image alt text

Transform Components(Transform组件)(PS:不知道翻译成变换组建好不好)

In Unity each GameObject has a Transform component, which gives the GameObject a position, rotation, and scale in the world.

Similarly in UE4, Actors have a Root Component, which can be any subclass of Scene Component. A Scene Component gives the Actor a location, rotation, and scale in the world which is applied hierarchically to all components underneath it. Many of the components that you will use are subclassed from Scene Component, because it is really useful to have a position!
类似的在UE4种,Actor有一个Root Component,它可以是Scene Component的任意子类。 Scene Component为Actor在世界中提供了位置、旋转和比例,并逐层应用于Actor下的所有组件。你会用到的组件,大部分是Scenne Component的子类,因为拥有位置信息十分有用。

Even if you place an Empty Actor, UE4 will create a "Default Scene Root" for that Actor, which is just a plain Scene Component. If you drop a new Scene component in of your own, it will replace the Default Scene Root.
即使你放置了一个Empty Actor,UE4也会为其创建一个"Default Scene Root" ,它也是一个简单的Scene Component。如果你你自己添加了一个写的Scene Component,他会替代掉Default Scene Root。

Compound Objects (复合对象)

In Unity, you create compound objects by constructing a hierarchy of GameObjects and parenting their transforms together:

image alt text

In UE4, you create compound game objects by nesting components hierarchically:

image alt text

As you can see from the diagram, nested hierarchies can be created by attaching Scene Components to one another, since they have a transform - similar to parenting transforms in Unity. Actor Components (the base-class for all components) can only be attached directly to the Actor itself.
从图表中你可以看到,可以通过依附另一个Scene Component来嵌套层级关系,因为它们有类似Unity中父子变换关系的transform。Actor组件(最基础的组件)可以可以直接依附到Actor本身上。

Do I build everything out of Components? (我是使用组件来构建任何东西吗?)

Its really up to you, but most often you will use a combination of custom component types along with Actor classes that use those components. We mentioned this earlier, but UE4 has many special types of Actors that guarantee a certain level of capability and always include certain components. For example, a Character always contains a Character Movement Component.
这取决于你,但是多数情况下,你会结合使用自定义的组件类型和使用这些组件的Actor类。早先我么提到过,但是UE4有很多特定类型的Actor,它们保证了所需的功能并包含了所需的组件。例如,Character包含了Character Movement Component

There are several sub-classed Actor types you will quickly encounter in the engine and are useful in almost every type of game. Here is a list of our most common built-in Actors:

  • Pawn - A type of Actor representing a controllable game object, typically the player's avatar. Pawns are moved by Players and AI alike through an owning Controller.

  • Character - A more specialized version of Pawn designed for biped avatars that handle a lot of the complexity of those kinds of game objects.

  • Controller - Possesses and controls a Pawn. By separating the Pawn from the controller, you can write AI Controllers that can manipulate a pawn using the same interface the player would.

  • Player Controller - A more specialized Controller designed for getting input from a player's Gamepad, Touch, or Mouse/Keyboard, and using that input to drive the Pawn or Character they possess.

    Pawn - 代表可被控制的游戏对象,通常被认为是玩家的化身。Pawn通过Player或AI Controller来控制移动。
    Character - 它是Pawn的扩展,专门针对两足动物及处理这类对象的复杂关系。
    Controller - 拥有并控制一个Pawn.为了区别Pawn和controller,你可以写个AI Controller来草种Pawn使用与Player相同的接口。
    Player Controller - 它是一种特殊的Controller,用来接收来自玩家的游戏手柄、触摸、或者鼠标\键盘的输入,并用这些输入来驱动它们所占有的Pawn或者Character。

So is everything an Actor? (所有的东西都是Actor?)

Not everything. Actors are most common class used for gameplay in UE4 and the only type that can be Spawned into the World. So everything you place in your level will be an Actor.

The other important type to know about is Object. Object is actually the base class of all Unreal classes, including Actor and many others. This is a much lower-level construct than Actor, but still has features that you will expect from a Unreal class, such as reflection andserialization. Object is a very basic class we use when we need to define a new type that just does not fit the mold of an Actor. For example, Actor Component is the base class for all Components, and derives from Object instead of Actor.
另外一个重要的类是Object。Obeject实际上是所有Unreal类的基类,包括 Actor 和 很多其他的东西。它被构造得比Actor低级,但还是有你需要的特性,比如反射和序列化。当我需要定义一个不符合 Actor 的类型时,Object会是我们使用的最基础的类。例如,Actor Component是所有组件的基类,却继承自Object,而不是Actor

What is this Gameplay Framework thing in UE4? (UE4种的Gameplay Framwork 是什么?)

Okay, so this is where things get a little crazy (in sort of an awesome way.) Unity gives you a clean slate to start designing your game, and Unreal does the same. In Unity you can build everything out of basic GameObjects and components, and in Unreal you can build everything out of Actors and components.
不错,事情开始有点有趣了(通过一个很棒的方式)。Unity和Urenal都是给你一张白纸来设计你的游戏。在Unity中,你可以通过GameObject和组件来构建所有东西,而在UE4中你则通过 Actor 和 组件来创建事物。

However Unreal has this extra layer on top called the Gameplay Framework. This does not really exist in Unity at all. You do not have to use it in Unreal, but it is actually super cool! Basically, if you make use of some basic primitive classes and follow certain established conventions, your game will acquire some awesome features automatically that would be otherwise very difficult to implement or retrofit (such as full multiplayer support!)
然而,UE4另外还有一个叫做 Gameplay Framework的扩展层。Unity压根就没这货。你并不一定要在UE4中使用它,但它确实很酷。基本上,如果你使用了很基础的原始类并遵循既定惯例,你的游戏将会自动获得一下额难以实现或改造的功能(如多人联机)。

Countless awesome games have been designed on top of Unreal's Gameplay Framework, and it is worth taking some time to understand how it works. Yes, you could roll your own version of this. That is totally fine if you want to! But hundreds of awesome Unreal developers have made great use of this framework in UE4 today, so it is worth taking some time to learn.
很多优秀的游戏都是基于Unreal的Gameplay Framework设计的,而花一点时间理解他的运作是很有必要的。嗯,你可以使用你自己的方法。如果你要的话会很好。但是,成千上万的Unreal优秀开发者都很好地用了这个框架,所以它确实值得花点时间去学一下。

To use the Gameplay Framework, you really just need to learn the customized built-in Actor classes included with Unreal, such as Pawn,Character, and Player Controller, and eventually learn about how Unreal replication and networking features work. For now, let us get back to the basics though.
为了使用Gameplay Framework,你必须学习Unreal所包含的自定义的内置Actor,比如 Pawn Character, 和 Player Controller, 甚至需要了解虚幻是如何工作的(PS:replication在这边如何翻译?)。现在,让我们回到基础部分。

How to write code in UE4 (在UE4中如何写代码)

So, I'm used to programming in MonoDevelop (哥习惯了在Unity的Monodevelop中编程)

For Blueprint scripting, you will only need Unreal Editor -- everything is built in! To write code in C++, download the free version of Visual Studio on Windows, or install Xcode on Mac. When you first create a new project (or add code to an existing project), UE4 will automatically create Visual Studio project files for you. You can open Visual Studio by double-clicking on a C++ class inside Content Browser, or by clicking the "Open Visual Studio" button in the main File menu.
对于蓝图编程,你只需要Unreal编辑器 —— 所有东西已被内置。对于C++代码,下载free version of Visual Studio 到 Window上,或者安装 install Xcode 到mac上。首次创建新项目(或添加代码到已有项目),UE4会自动为你创建VS工程。你只需要双击Content Browser中的C++文件就可以打开VS了,后者点击File菜单中的 "Open Visual Studio" 。

image alt text

One important difference in UE4: You will sometimes have to manually refresh your Visual Studio project files (for example, after downloading a new version of UE4, or when manually making changes to source file locations on disk.) You can do this by clicking "Refresh Visual Studio Project" in the main menu, or by right-clicking on the .uproject file in your project's directory and selecting "Generate Visual Studio project files"
在UE4有一点不同的是:有时候你需要手动更新你的VS项目文件(例如,下载了新版本的UE4,或者手动改变了源文件的路径)。你可以点击主菜单中的"Refresh Visual Studio Project" ,或者右键项目目录下的.uproject文件选择"Generate Visual Studio project files"。

image alt text

Writing Event Functions (Start, Update, etc.) (编写事件方法(Start、Update 等等))

If you are used to working with MonoBehaviors you are used to such methods as Start, Update, and OnDestroy. Here is a comparison between a Unity behavior and its counterpart in UE4 Actors and components.
如果你习惯了Monobehaviors,你也就习惯了Start() 、update() 、Ondestroy() 这些方法。下面是 Unity 和Unreal 对应术语的一个比较。

In Unity, we might have a simple component that looks like this:

public class MyComponent : MonoBehaviour
    void Start() {}
    void OnDestroy() {}
    void Update() {}

But remember, in UE4 you can write code right on the Actor itself rather than only coding new component types. This is actually very common and useful.

Similar to Unity's Start, OnDestroy, and Update functions, we have a similar set of methods for Actors in UE4:
类似于 Unity 的Start() 、update() 、Ondestroy() 方法,我们在UE4种也有相应的方法。

C++ :

class AMyActor : public AActor

    // Called at start of game.
    void BeginPlay();

    // Called when destroyed.
    void EndPlay(const EEndPlayReason::Type EndPlayReason);

    // Called every frame to update this actor.
    void Tick(float DeltaSeconds);

Blueprint :


Components in UE4 contain different functions. Here is a simple example:

C++ :

class UMyComponent : public UActorComponent

    // Called after the owning Actor was created
    void InitializeComponent();

    // Called when the component or the owning Actor is being destroyed
    void UninitializeComponent();

    // Component version of Tick
    void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction);

Blueprint :


Remember, in UE4 it is important to call the parent class' version of method.

For example, in Unity C# this would be called base.Update(), but in UE4 C++ we will use Super::TickComponent():
例如,在Unity中的C#会调用 base.Update() ,但是UE4种的C++会使用 Super::TickComponent():

void UMyComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
    // Custom tick stuff here
    Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

You may have noticed some things begin with "A" and others with "U" in C++. The prefix "A" indicates an Actor sub-class. Where as the prefix "U" indicates an Object sub-class. There are some other prefixes too, for example "F" is used for most plain data structures or non-UObject classes.
你可能会注意到C++中诸如 “A” 和 “U” 的前缀。前缀 “A” 表示Actor的子类,前缀 “U” 表示 Object的紫了。这里还有其他前缀,比如 “F” 便是简单的数据结构 或者不是 UObject 的其他类。

Writing gameplay code in UE4 (在UE4中编写游戏代码)

Okay, things are going to get a bit deeper from here on out. We will be talking about programming topics that are critical for creating games. Because you know Unity, we will be explaining features with slant toward C# users learning Unreal C++, but you can use Blueprint Scripting for pretty much everything if you want! We have added examples in both C++ and Blueprint where possible.
嗯,从这里开始要更加深入了。我们将讨论对创建游戏至关重要的编程话题。由于你了解Unity,我们偏向学习 Unreal C++ 的C#同学来解释这些特性,但你可以使用蓝图来创建你想要的一切。可能的话,我们会添加既有C++又有蓝图的例子。

Let us talk about some of the most common gameplay programming patterns and how you would approach them in Unreal. Many functions in Unity have a comparable function in Unreal that should seem familiar. We will go through the most common functions one by one.

Instantiating GameObject / Spawning Actor (实例化 GameObject / 生成 Actor)

In Unity, we use the Instantiate function to create new instances of objects.
在Unity中,我们使用 Instantiate 方法来实例化对象

This function takes any UnityEngine.Object type (GameObject, MonoBehaviour, etc.), and makes a copy of it.
这个方法适用于所有的 UnityEngine.Object 类型(GameObject, MonoBehaviour,等等),并对其实现复制功能。

public GameObject EnemyPrefab;
public Vector3 SpawnPosition;
public Quaternion SpawnRotation;

void Start()
    GameObject NewGO = (GameObject)Instantiate(EnemyPrefab, SpawnPosition, SpawnRotation); = "MyNewGameObject";

In UE4, there are a couple different functions to instantiate objects, depending on your needs. NewObject is used for creating new UObject types, and SpawnActor is used for spawning AActor types.
在UE4中,有几个不同的方法可以实例化对象,这取决于你所需要的。 NewObject 用于创建新的 UObject类型, SpawnActor 用于创建类型 AActor 

First we will briefly talk about UObjects and NewObject. Subclassing UObject in Unreal is much like subclassing ScriptableObject in Unity. They are useful for gameplay classes that do not need to spawn into the world or have attached components like Actors do.
首先,我们需要简单说明下 UObjects 和 NewObjec 。Unreal 子类化 UObject 类似于 Unity 子类化 ScriptableObject。它们对于不需要生成到世界中或者依附类似Actor组件的游戏类 很有用。

In Unity, if you created your own subclass of ScriptableObject, you may instantiate it like this:
在 Unity 中,如果你创建了自己的ScriptableObject子类,你可能需要这样来实例化:

MyScriptableObject NewSO = ScriptableObject.CreateInstance<MyScriptableObject>();

And in Unreal, if you created your own UObject derived type, you may instantiate it like this:
而在UE4种,如果你想要创建自己的 UObject 派生类,你会这样实例化:

UMyObject* NewObj = NewObject<UMyObject>();

So what about Actors? Actors are spawned using the SpawnActor method on a World (UWorld in C++) object. How do you get the World object? Some UObjects provide a GetWorld method for you, as an example, all Actors do.
那对于 Actor 来说呢?Actor 是使用 SpawnActor 方法生成 World 对象的(C++ 中的 Uworld)。你是如何获得 World 对象的。一些 UObject 提供了GetWorld 方法,比如所有 Actor 都提供了这个方法。

You will notice instead of passing in another Actor, we pass in the "class" of the Actor we want to spawn. In our example, the class can be any subclass of AMyEnemy.
你会发现我们是通过 Actor 的 类而不是 另一个 Actor 来生成的。在我们的例子中。这个类可以是任何 AMyEnemy 的子类。

But what if you want to make a "copy" of another object, like what Instantiate allows you to do?
但是如果你想像 Instantiate 那样来获得另一个对象的 复制体呢?

The NewObject and SpawnActor functions can also be given a "template" object to work with. Unreal will make a copy of that object, instead of making one "from scratch". This will copy over all of its UPROPERTYs and components.
NewObject 和 SpawnActor 方法都提供了一个 “模板”。UE4会直接复制对象,而不是从头开始建一个。这样拷贝他所有的 UPROPERTY 和 组件。

AMyActor* CreateCloneOfMyActor(AMyActor* ExistingActor, FVector SpawnLocation, FRotator SpawnRotation)
    UWorld* World = ExistingActor->GetWorld();
    FActorSpawnParameters SpawnParams;
    SpawnParams.Template = ExistingActor;
    World->SpawnActor<AMyActor>(ExistingActor->GetClass(), SpawnLocation, SpawnRotation, SpawnParams);

You might be wondering what "from scratch" means in this context. Each object class you create has a default template that contain default values for its properties and components. If you do not override these properties and do not provide your own template, Unreal will use these default values to construct your object. To help illustrate this, let us first look at a MonoBehaviour for example:
你可能会对文中的 “从头开始” 不是很理解。 你创建的每个对象类都用一个默认的模板,它包含了物体属性和组件的默认值。如果你不重写这些属性,也不提供你自己的模板,UE4将会使用这些默认值来构建你的对象。为了帮助理解,让我们先看看Monobehavia的例子吧。

public class MyComponent : MonoBehaviour
    public int MyIntProp = 42;
    public SphereCollider MyCollisionComp = null;

    void Start()
        // Create the collision component if we don't already have one
        if (MyCollisionComp == null)
            MyCollisionComp = gameObject.AddComponent<SphereCollider>();
            MyCollisionComp.radius = 20.0f;

In the above example, we have an int property that defaults to 42, and a SphereCollider component that defaults to a radius of 20.
在上面的例子中,我们有一个默认值为42的整型属性,和一个 默认半径为20的 SphereCollider 组件。

We can achieve the same thing in Unreal using the object's constructor.

class AMyActor : public AActor

    int32 MyIntProp;

    USphereComponent* MyCollisionComp;

        MyIntProp = 42;

        MyCollisionComp = CreateDefaultSubobject<USphereComponent>(FName(TEXT("CollisionComponent"));
        MyCollisionComp->RelativeLocation = FVector::ZeroVector;
        MyCollisionComp->SphereRadius = 20.0f;

In the constructor of AMyActor, we have set the default property values for the class. Note the use of the CreateDefaultSubobject function. We can use it to create components and assign default properties to them. All the subobjects we create using this function act as a default template, so we can modify them in a subclass or Blueprint.
在 AmyActor 的构造函数中,我们为类设置了默认的属性值。注意  CreateDefaultSubobject 方法的使用。我们可以使用它来创建组件,并为其指定默认属性。我们使用这个方法创建的子对象就是一个默认模板,因此我们可以在子类或蓝图中修改它们。

Casting from one Type to Another (类型转换)

In this case, we get a component we know we have, then cast it to a specific type and conditionally do something.

Unity C#:

Collider collider = gameObject.GetComponent<Collider>;
SphereCollider sphereCollider = collider as SphereCollider;
if (sphereCollider != null)
        // ...

UE4 C++:

UPrimitiveComponent* Primitive = MyActor->GetComponentByClass(UPrimitiveComponent::StaticClass());
USphereComponent* SphereCollider = Cast<USphereComponent>(Primitive);
if (SphereCollider != nullptr)
        // ...

Destroying GameObject / Actor  (销毁GameObject / Actor)

Unity C++ Blueprint


Destroying GameObject / Actor (With 1 Second Delay) (延时1s销毁GameObject / Actor)

Unity C++ Blueprint
Destroy(MyGameObject, 1);

Click for full view.

Disabling GameObjects / Actors (禁用 GameObject / Actor)

Unity C++ Blueprint
// Hides visible components

// Disables collision components

// Stops the Actor from ticking

Click for full view.

Accessing the GameObject / Actor from Component (通过组件访问 GameObject / Actor)

Unity C++ Blueprint
GameObject ParentGO = 
 AActor* ParentActor = 

Click for full view.

Accessing a Component from the GameObject / Actor (通过 GameObject / Actor 访问组件)


MyComponent MyComp = gameObject.GetComponent<MyComponent>();


UMyComponent* MyComp = MyActor->FindComponentByClass<UMyComponent>();



Finding GameObjects / Actors (搜索 GameObject / Actors)

// Find GameObject by name 通过名字
GameObject MyGO = GameObject.Find("MyNamedGameObject");

// Find Objects by type  通过类型
MyComponent[] Components = Object.FindObjectsOfType(typeof(MyComponent)) as MyComponent[];
foreach (MyComponent Component in Components)
        // ...

// Find GameObjects by tag 通过标签
GameObject[] GameObjects = GameObject.FindGameObjectsWithTag("MyTag");
foreach (GameObject GO in GameObjects)
        // ...
// Find Actor by name (also works on UObjects) 
AActor* MyActor = FindObject<AActor>(nullptr, TEXT("MyNamedActor"));

// Find Actors by type (needs a UWorld object) 
for (TActorIterator<AMyActor> It(GetWorld()); It; ++It)
        AMyActor* MyActor = *It;
        // ...

image alt text

// Find UObjects by type
for (TObjectIterator<UMyObject> It; It; ++it)
    UMyObject* MyObject = *It;
    // ...

// Find Actors by tag (also works on ActorComponents, use TObjectIterator instead)
for (TActorIterator<AActor> It(GetWorld()); It; ++It)
    AActor* Actor = *It;
    if (Actor->ActorHasTag(FName(TEXT("Mytag"))))
        // ...

image alt text

Adding tags to GameObjects / Actors (添加标签给 GameObject / Actors)

MyGameObject.tag = "MyTag";

// Actors can have multiple tags

image alt text

Adding tags to MonoBehaviours / ActorComponents  (添加标签给 MonoBehaviours / ActorComponent)

// This changes the tag on the GameObject it is attached to
MyComponent.tag = "MyTag";

// Components have their own array of tags

Comparing tags on GameObjects / Actors and MonoBehaviours / ActorComponents  (GameObjects / Actors 和 MonoBehaviours / ActorComponents 上的标签比较)  获取 bool 值

if (MyGameObject.CompareTag("MyTag"))
    // ...

// Checks the tag on the GameObject it is attached to
if (MyComponent.CompareTag("MyTag"))
    // ...

// Checks if an Actor has this tag
if (MyActor->ActorHasTag(FName(TEXT("MyTag"))))
    // ...

image alt text

// Checks if an ActorComponent has this tag
if (MyComponent->ComponentHasTag(FName(TEXT("MyTag"))))
    // ...

image alt text

Physics: RigidBody vs. Primitive Component  (物理:Rigidbody 对比 Primitive组件)

In Unity to give any GameObject physics characteristics, you first give it a RigidBody component. In Unreal, any PrimitiveComponent (UPrimitiveComponent in C++) can be a physical object. Some common Primitive Components are ShapeComponents (Capsule, Sphere, Box), StaticMeshComponent, and SkeletalMeshComponent.
在 Unity 中,你首先需要给 GameObject 添加 Rigidbody 来为其添加物理特性。在UE4种,任何  PrimitiveComponent 都是一个物理对象。 有些  PrimitiveComponent 是ShapeComponents (胶囊、球体、立方体),StaticMeshComponent 和 SkeletalMeshComponent。

Unlike Unity which separates the responsibilities of collision and visualizations into separate components. Unreal combines the concepts of the potentially physical and the potentially visible into PrimitiveComponent. Any component that would have any geometry in the world, that could either be rendered or interacted with physically sub-classes from PrimitiveComponent.
不同于 Unity 中将碰撞与可视化调节分开,UE4 把物理概念和可视化概念结合到了 PrimitiveComponent 上。World 中任何有几何形状的 组件,都可以被渲染或与  PrimitiveComponent 的子类进行交互。

Layers vs Channels  Unity 的 Layer 和 UE4 的 Channels

In Unity, they are called "Layers". UE4 uses Collision Channels, and they work in a similar way. You can read up on them here.
在 Unity 中 叫做 “Layers”. UE4使用 Collision Channels (碰撞通道)。它们很相似,你可以在这里获取更多的信息。

RayCast vs RayTrace  (射线)

Unity C#:

GameObject FindGOCameraIsLookingAt()
    Vector3 Start = Camera.main.transform.position;
    Vector3 Direction = Camera.main.transform.forward;
    float Distance = 100.0f;
    int LayerBitMask = 1 << LayerMask.NameToLayer("Pawn");

    RaycastHit Hit;
    bool bHit = Physics.Raycast(Start, Direction, out Hit, Distance, LayerBitMask);

    if (bHit)
        return Hit.collider.gameObject;

    return null;

UE4 C++:

APawn* AMyPlayerController::FindPawnCameraIsLookingAt()
    // You can use this to customize various properties about the trace
    FCollisionQueryParams Params;
    // Ignore the player's pawn

    // The hit result gets populated by the line trace
    FHitResult Hit;

    // Raycast out from the camera, only collide with pawns (they are on the ECC_Pawn collision channel)
    FVector Start = PlayerCameraManager->GetCameraLocation();
    FVector End = Start + (PlayerCameraManager->GetCameraRotation().Vector() * 1000.0f);
    bool bHit = GetWorld()->LineTraceSingle(Hit, Start, End, ECC_Pawn, Params);

    if (bHit)
        // Hit.Actor contains a weak pointer to the Actor that the trace hit
        return Cast<APawn>(Hit.Actor.Get());

    return nullptr;

UE4 Blueprint:

Click for full view.

Triggers (触发器)

Unity C#:

public class MyComponent : MonoBehaviour
    void Start()
        collider.isTrigger = true;
    void OnTriggerEnter(Collider Other)
        // ...
    void OnTriggerExit(Collider Other)
        // ...

UE4 C++:

class AMyActor : public AActor

    // My trigger component
    UPrimitiveComponent* Trigger;

        Trigger = CreateDefaultSubobject<USphereComponent>(TEXT("TriggerCollider"));

        // Both colliders need to have this set to true for events to fire
        Trigger.bGenerateOverlapEvents = true;

        // Set the collision mode for the collider
        // This mode will only enable the collider for raycasts, sweeps, and overlaps

    void BeginPlay()
        // Register to find out when an overlap occurs
        OnActorBeginOverlap.AddDynamic(this, &AMyActor::OnTriggerEnter);
        OnActorEndOverlap.AddDynamic(this, &AMyActor::OnTriggerExit);


    void EndPlay(const EEndPlayReason::Type EndPlayReason)
        OnActorBeginOverlap.RemoveDynamic(this, &AMyActor::OnTriggerEnter);
        OnActorEndOverlap.RemoveDynamic(this, &AMyActor::OnTriggerExit);


    void OnTriggerEnter(AActor* Other);

    void OnTriggerExit(AActor* Other);

UE4 Blueprint:

image alt text

You can read more about setting up collision responses here.

Kinematic Rigidbodies (刚体运动学)

Unity C#:

public class MyComponent : MonoBehaviour
    void Start()
        rigidbody.isKinimatic = true;
        rigidbody.velocity = transform.forward * 10.0f;

In UE4, The collision component and rigidbody component are one. The base class for this is UPrimitiveComponent, which has many subclasses (USphereComponent, UCapsuleComponent, etc.) to suit your needs.
在UE4中,碰撞组件和刚体组件是同一个组件,它们的基类是 UPrimitiveComponent ,它有很多子类(USphereComponent, UCapsuleComponent等等)  可以满足你的需求。

UE4 C++:

class AMyActor : public AActor

    UPrimitiveComponent* PhysicalComp;

        PhysicalComp = CreateDefaultSubobject<USphereComponent>(TEXT("CollisionAndPhysics"));
        PhysicalComp->SetPhysicsLinearVelocity(GetActorRotation().Vector() * 100.0f);

Input events (输入事件)

Unity C#:

public class MyPlayerController : MonoBehaviour
    void Update()
        if (Input.GetButtonDown("Fire"))
            // ...
        float Horiz = Input.GetAxis("Horizontal");
        float Vert = Input.GetAxis("Vertical");
        // ...

UE4 C++:

class AMyPlayerController : public APlayerController

    void SetupInputComponent()

        InputComponent->BindAction("Fire", IE_Pressed, this, &AMyPlayerController::HandleFireInputEvent);
        InputComponent->BindAxis("Horizontal", this, &AMyPlayerController::HandleHorizontalAxisInputEvent);
        InputComponent->BindAxis("Vertical", this, &AMyPlayerController::HandleVerticalAxisInputEvent);

    void HandleFireInputEvent();
    void HandleHorizontalAxisInputEvent(float Value);
    void HandleVerticalAxisInputEvent(float Value);

UE4 Blueprint:

image alt text

This is what your input properties in your Project Settings might look like:
你的Project Settings中的输入属性应该是这样的:

image alt text

You can read more about how to setup input here.

FAQ (常见问题)

How do I load my last project automatically?  怎么自动加载我上次的项目?

If you are used to Unity automatically loading the last project you were working on, the same is possible in UE4. To enable, check "Always load last project on Startup" when opening a project. You can also toggle the setting at any time from the main Edit menu under Edit/Editor Preferences/Loading and Saving/Startup.
如果你习惯了 Unity 自动加载上次的项目,你可以在UE4打开项目的时候勾选 "Always load last project on Startup" .你也可以在 Edit/Editor Preferences/Loading and Saving/Startup 主菜单下进行设置。

Where do I set Input Bindings for my game?  在哪里为我的游戏设置输入绑定?

In Unity, you are used to using the Input Manager settings for Project to setup default bindings. In UE4 it works similarly. You will open your Project Settings then select the Input category. There, you can add various buttons (actions) and analog controls (axes). Give each control a name and default binding. Then, you can get callbacks to your game's Pawn when the input events are triggered. Check out the Input documentation page for the details.
在Unity 中,你会习惯 Input Manager settings 来设置默认绑定。在 UE4 中,你可以的打开 Project Settings 选中 Input 类别。在这里,你可以添加各种按键(actions)和模拟量控制(Axes). 设置名称和默认绑定。然后,你可以在输入事件被触发时获取回调函数。详细资料见 Input documentation page 。

How do I change the starting scene of my project? 如何改变我的启动场景?

You can change the startup map of your project from the project settings tab. From the main menu choose Edit/Project Settings->Maps & Modes to change the starting map.
你可以在 Edit/Project Settings->Maps & Modes  设置启动场景。

How do I run my game? 如何运行我的游戏?

The easiest way to run your game is to click the "Play" button on the the main editor toolbar, which will run the game right inside the editor's process. If you want to run it as a standalone application, click the dropdown arrow next to "Play" and choose "Standalone Game". Finally, if you want to run on a mobile device or in a web browser, you will use the "Launch" button on the toolbar (after installing any prerequisites that are needed for that platform.)
最简单的方法是点击主编辑器工具栏上的 “Play”  ,它会直接在编辑器中运行游戏。如果你想使它独立的应用运行的话,你可以 点击 “Play” 下拉菜单中的 "Standalone Game" 。最后,如果你想要让它在移动设备或浏览器中运行,你需要使用 “Launch” 按键(在安装个平台所需要的包之后)。

What units are these?  它们使用了什么单位的?

In Unity, the primary unit of measurement is one meter. In UE4, the primary unit of measurement is one centimeter.
Unity 的主要单位是米,UE4 的主要单位是厘米。

So if you move something 1 unit (meter) in unity that is equivalent to moving something 100 units (centimeters) in UE4.
所以在 Unity 中一个单位 等效于 UE4 中移动一百个单位。

If you want to move something 2 Feet in Unity that would be 0.61units (meter) and in UE4 is 61 units (centimeters).
如果你想在 Unity 中移动两尺(约0.61个单位(米)),相当于 UE4 中的61个单位。

What is with this coordinate system? Which way is up? 坐标系是怎样的?那个方向朝上?

Both Unity and UE4 use a left-handed coordinate system, but the axes are swapped around. In UE4, positive X is "forward", positive Y is "right" and positive Z is "up". This cannot be changed, so you will have to get used to it.
Unity 和 UE4 都使用了左上坐标系,但是轴向有所不同。在 UE4 中 ,X:向前 —— Y:向右 —— Z:向上 。这无法改变,所以你需要适应它。

How do I see Log Output from my game? 怎么看我的调试日志输出信息?

In the UE4 editor, you can open the "Output Log" from the "Window -> Developer Tools" menu. You can also run your game with the "-log" command-line parameter to summon a dedicated log window alongside your game, which is really useful!
在UE4 编辑器,你可以在  "Window -> Developer Tools"  菜单打开  "Output Log" 。你也可以通过 “-log” 命令行参数来调出一个单独的日志窗口,它非常的有用。

Speaking of Log Output, where is my Debug.Log?  输出信息到 Log Output,我的 Debug.Log() 函数呢?

Logging in UE4 is highly customizable. Read up on how to log messages here.

How do I throw exceptions? 如何抛出异常?

In Unity, you are used to throwing exceptions when things go wrong. UE4 does not use exception handling. Instead, use the 'check()' function to trigger a critical assertion error. You can pass in an error message. If you want to report an error but not halt the program, use 'ensure()' instead. This will log an error with a full call stack, but program execution will continue. If you had a debugger attached, both functions will break into the debugger.
在 Unity 中 ,你可以在发生错误的时候抛出异常。 UE4 并不使用异常处理机制。而是使用 “ check() ” 方法来触发一个关键错误声明。你可以传递一个错误消息。如果你想报告一个错误但不停止程序,可以使用 “ ensure() ” .这将使用完整的调用栈来记录错误,但是程序将继续执行。如果你有一个附加的调试器,这两个方法都会进入调试器中。

Where is the .NET Framework?  NEt Framwork 框架在哪里?

Unlike Unity, UE4 does not use the .NET framework. UE4 has its own set of container classes and libraries. Common container comparisons:
不同于 Unity ,UE4 并不使用 。NET Framwork 。UE4 有自己的容器类和库。常见的容器比较:

.Net Framework UE4
String FStringFText
List TArray
Dictionary TMap
HashSet TSet

You can learn more about other UE4 containers here.

Does Unreal automatically reload code changes? UE4会自动更新变化的代码吗?

Yes! You can leave the editor open while you write code. Simply kick off a compile from Visual Studio after you have finished editing code, and the editor will "hot reload" your changes automatically. You can also click the Compile button on the editor's main toolbar. That can be useful when you have the Visual Studio debugger attached.
可以。你可以在你写代码的时候让 UE4 编辑器开着。写好代码后,简单地在Visual Studio里编译,编辑器会自动“热更新”的已改变的代码 。您也可以点击编辑器主工具栏上的 Compile 按钮。当你有Visual Studio调试器时,这是很有用的。 

Where to go from here  下一步该去哪儿?

Thanks for reading the guide! This was created for the Unreal community with the help of Unreal developers everywhere, and we very much appreciate any feedback and corrections you can offer. We will try to keep improving this document as we learn more about what is most helpful when transitioning to UE4!
感谢阅读本文! 这是在无处不在的虚幻开发者的帮助下为虚幻社区创建的文档,我们非常感激您提供的任何反馈和修正。我们会保持文档的改进。

We have many additional UE4 learning resources available!