Prepare for an Unity 3D (Game Developer / AR, VR Developer) Interview 2



Unity Engine Specific Question


Q1. Difference between Start and Awake Unity Events

Awake as “initialize me” and Start as “initialize my connections to others.” You can’t rely on the state of other objects during Awake, since they may not have Awoken themselves yet, so it’s not safe to call their methods.

Start function is called only if the script component is enabled. Awake function called when the script instance is being loaded.

If the script is NOT enabled at the beginning of your game, and you don’t need the variables to be initialized, start() would be saving performance as awake() would be called regardless.

 

Q2. Difference between Update, Fixed Update and Late Update.

Update:  (Most things)

  • Update is called once per frame from every script in which it is defined. Calling of Update function is dependent on the frame rate.
  • The time interval to call update is not fixed; it depends on how much time required to complete the individual frame.

FixedUpdate: (Physics things)

  • FixedUpdate is independent of the frame rate. The time interval is to call FixedUpdate is constant; as it is called on a reliable timer.
  • FixedUpdate can be called multiple times per frame if frame rate is low or it may not be called per frame if the frame rate will be high.
  • All the physics related calculations and updates are called immediately after FixedUpdate. So, its good to handle all physics related calculation inside FixedUpdate.

LateUpdate: (After update)

  • LateUpdate is also called per frame. It is called after all other Update functions.
  • This is useful to ensure all other Update related calculation is complete and other dependent calculation can be called.
  • For example, if you need to integrate a third-person camera to follow any object; then it should be implemented inside the LateUpdate. It is make sure that camera will track the object after its movement and rotation update.

 

Q3. Explain Unity-Mono Script Lifecycle / Execution Order of Event Functions

In Unity scripting, there are a number of event functions that get executed in a predetermined order as a script executes. This execution order is described below:

  1. Awake(): This function is always called before any Start functions and also just after a prefab is instantiated.
  2. OnEnable(): This function is called just after the object is enabled. This happens when a MonoBehaviour instance is created, such as when a level is loaded or a GameObject with the script component is instantiated.
  3. Start(): Start is called before the first frame update only if the script instance is enabled.
  4. FixedUpdate(): FixedUpdate is often called more frequently than Update. It can be called multiple times per frame
  5. Update(): Update is called once per frame. It is the main workhorse function for frame updates.
  6. LateUpdate(): LateUpdate is called once per frame, after Update has finished. Any calculations that are performed in Update will have completed when LateUpdate begins.
  7. OnGUI(): Called multiple times per frame in response to GUI events.
  8. OnApplicationQuit(): This function is called on all game objects before the application is quit. In the editor it is called when the user stops playmode.
  9. OnDisable(): This function is called when the behaviour becomes disabled or inactive.
  10. OnDestroy(): This function is called after all frame updates for the last frame of the object’s existence (the object might be destroyed in response to Object.Destroy or at the closure of a scene).

 

Q4. What is time.deltatime in Unity explain the use of deltatime?

In unity, Time.deltaTime will provide you time in seconds it took to complete the last frame (Read Only). This can be used to make your game frame independent.

When you multiply any value with Time.deltaTime you essentially express: I want to move this object 10 meters per second instead of 10 meters per frame.

For more details please visit  “Edit -> Project Settings -> Time” OR From scripting, check out the Time class.

public class ExampleClass : MonoBehaviour {
    void Update() {
        float translation = Time.deltaTime * 10;
        transform.Translate(0, 0, translation);
    }
}

 

Q5. What is Coroutine, is it running on a new thread?

While Coroutines seem to work like threads at first glance, they actually aren’t using any multithreading. They are executed sequentially until they yield. Coroutine might seem like it is a thread, but coroutines execute within the main thread.

The difference between a coroutine and a thread is very much like the difference between cooperative multitasking and preemptive multitasking. Note that a coroutine runs on the main thread and must voluntarily yield control back to it, if control is not yielded (this is where the coroutine must be cooperative) then your coroutine will hang your main thread, thus hanging your game.

The disadvantage of not doing “real” multithreading is that you can not use coroutines to parallelize CPU-intense calculations over multiple CPU cores.  With the release of Unity 2017, it is now possible to use a new C# feature called async-await for our asynchronous methods instead. This comes with a lot of nice features compared to coroutines.

Let’s look at a simple example. Given the following coroutine:

1
2
3
4
5
6
7
8
9
public class AsyncExample : MonoBehaviour
{
    IEnumerator Start()
    {
        Debug.Log("Waiting 1 second...");
        yield return new WaitForSeconds(1.0f);
        Debug.Log("Done!");
    }
}

The equivalent way to do this using async-await would be the following:

1
2
3
4
5
6
7
8
9
public class AsyncExample : MonoBehaviour
{
    async void Start()
    {
        Debug.Log("Waiting 1 second...");
        await Task.Delay(TimeSpan.FromSeconds(1));
        Debug.Log("Done!");
    }
}

Conclusion:

  • If you want to use asynchronous execution to express game logic, use coroutines.
  • If you want to use asynchronous execution to utilize multiple CPU cores, use threads.

 

Q6. Difference between Static and Dynamic Batching.

To draw a GameObject on the screen, the engine has to issue a draw call to the graphics API (such as OpenGL or Direct3D). Draw calls are often resource-intensive. Unity deal with draw call using the following two techniques.

  • Dynamic batching: for small enough Meshes, this transforms their vertices on the CPU, groups many similar vertices together, and draws them all in one go.
  • Static batching: combines static (not moving) GameObjects into big Meshes, and renders them in a faster way.

 

Q7. Difference between Destroy and DestroyImmediate unity function

The purpose of both functions is same, to destoy gameobject, but there isa very small difference, which is very crucial to understand, wrong use of these function can cause your app to crash

Destroy():

  • This just destroys the game object passed as a parameter.
  • It set all the references to that game object to null at the end of the frame.
  • Syntax: Destroy(myGameObject);

DestroyImmediate():

  • As the name suggest it immediately destroy the gameobject passed as a parameter.
  • It set all the references to that game object to null immediately, it will not wait for the frame to end like Destroy() function.
  • Syntax: DestroyImmediate(myGameObject);

 

Q8. Is this possible to collide two mesh collider, if yes then How?

A mesh collider allows you to do collision detection between meshes and primitives. BitTwo mesh colliders cannot have interaction unless at least one of them is convex. You need to add ‘convex‘ mesh colliders and a ‘rigid body‘ to at least one of them.

 

Q9. Difference between unity scripting backend IL2CPP and Mono2x

Information is based on Unity version 2018.2:

IL2CPP (Intermediate Language To C++) is a Unity-developed scripting backend which you can use as an alternative to Mono when building projects for various platforms. IL2CPP (An ahead-of-time (AOT) compiler) supports debugging of managed code in the same way as the Mono scripting backend.

When building a project using IL2CPP, Unity converts IL code from scripts and assemblies to C++, before creating a native binary file (.exe, apk, .xap, for example) for your chosen platform. Some of the uses for IL2CPP include increasing the performance, security, and platform compatibility of your Unity projects.

Each Scripting Backend has benefits and drawbacks that should influence your decision on which is the right choice for your situation:

IL2CPP:

  • Code generation is heavily improved compared to Mono.
  • Debugging Script code in C++ from top to bottom is possible.
  • You can enable Engine code stripping to reduce code size.
  • Build times are longer than with Mono.
  • Only supports Ahead of Time (AOT) compilation.

Mono:

  • Faster build times than IL2CPP.
  • Supports more managed libraries due to Just In Time compilation (JIT).
  • Supports runtime code execution.
  • Must ship managed assemblies (.dll files that mono- or .net- produces).

IMP Points:

  • The default Target Architecture in the Android Player Settings are armv7 and x86 with the IL2CPP and Mono Scripting Backend.
  • Mono is not supported on UWP or iOS 11 and above. The default Architecture in the iOS Player Settings are armv7 and arm64 with the IL2CPP Scripting Backend.
  • UWP build only support IL2CPP and .NET, The .NET scripting backend (Deprecated ) uses Microsoft’s .NET to power scripting.

Unity Editor Related Question


Q1. Explain special folders  inside unity

Unity reserves some project folder names to indicate that the contents have a special purpose. There are a number of folder names that Unity interprets as an instruction that the folder’s contents should be treated in a special way. Some of these folders have an effect on the order of script compilation. These folder names are:

  • Assets: The Assets folder is the main folder that contains the Assets used by a Unity project.
  • Editor: Scripts placed in a folder called Editor are treated as Editor scripts rather than runtime scripts. These scripts add functionality to the Editor during development, and are not available in builds at runtime.
  • Editor default resources: Editor scripts can make use of Asset files loaded on-demand using the EditorGUIUtility.Load function. This function looks for the Asset files in a folder called Editor Default Resources.
  • Gizmos: Gizmos allow you to add graphics to the Scene View to help visualise design details that are otherwise invisible.
  • Plugins: You can add plug-ins to your Project to extend Unity’s features. Plug-ins are native DLLs that are typically written in C/C++. They can access third-party code libraries, system calls and other Unity built-in functionality.
  • Resources: You can load Assets on-demand from a script instead of creating instances of Assets in a Scene for use in gameplay. You do this by placing the Assets in a folder called Resources. Load these Assets by using the Resources.Load function.
  • Standard Assets: When you import a Standard Asset package (menu: Assets > Import Package) the Assets are placed in a folder called Standard Assets
  • StreamingAssets: You may want the Asset to be available as a separate file in its original format although it is more common to directly incorporate Assets into a build. To do so, place a file in a folder called StreamingAssets, so it is copied unchanged to the target machine, where it is then available from a specific folder.

 

Q2. Script compilation order inside Unity

There are four separate phases of script compilation. The phase where a script is compiled is determined by its parent folder. In a script compilation, the basic rule is that anything that is compiled in a phase after the current one cannot be referenced. Anything that is compiled in the current phase or an earlier phase is fully available.

The phases of compilation are as follows:

  • Phase 1: Runtime scripts in folders called Standard AssetsPro Standard Assets and Plugins
  • Phase 2: Editor scripts in folders called Editor that are anywhere inside top-level folders called Standard AssetsPro Standard Assets and Plugins.
  • Phase 3: All other scripts that are not inside a folder called Editor.
  • Phase 4: All remaining scripts (those that are inside a folder called Editor).

A common example of the significance of this order occurs when a UnityScript file needs to reference a class defined in a C# file. To achieve this, you need to place the C# file inside a Plugins folder, and the UnityScript file in a non-special folder. Because C# code is compiled before JS code, so in general, while JS code can access C# classes, the opposite is not possible If you don’t do this, an error is thrown saying that the C# class cannot be found.

 

Q3. Explain What Is Prefabs In Unity 3d?

Prefab in Unity 3D is referred for pre-fabricated object template (Class combining objects and scripts). At design time, a prefab can be dragged from project window into the scene window and added the scene’s hierarchy of game objects. If desired the object then can be edited.

At the runtime, a script can cause a new object instance to be created at a given location or with a given transform set of properties.

 

Q4. What is the difference betweenAsset Bundles, Resources and StreamingAssets Folder?

There are several ways to serve up resources to Unity at runtime, and each method has its place in game development: asset bundles, resource folders, and streaming assets.

# Asset Bundles:
Asset bundles let you deliver content to your application outside of your Unity build. Generally, you’d host these files on a remote web server for users to access dynamically. Asset bundles can contain anything from individual assets to entire scenes, which also makes them ideal for delivering downloadable content (DLC) for your game.

# Resource Folders:
The Resource folders are bundled managed assets. That means they will be compressed by Unity, following the settings you apply in the IDE. Unlike Asset bundles, resource folders are baked into the Unity Player as part of the game. You can do this by adding the required assets to a folder named Resources in your assets directory.

# Streaming Assets:
Like Resource Folders, a Streaming Assets directory can be created by intuitively creating a folder named StreamingAssetsthat, that you can use to put bundled un-managed assets. Unlike Resource folders, this directory remains intact and accessible in the Unity player. This creates a unique access point for users to add their own files to the game.

 

 

C# Related Question


Q1. Difference between Class and Structure.

One of the basic design decisions every framework designer faces is whether to design a type as a class (a reference type) or as a struct (a value type).

Similarities:

  • Both are container types, meaning that they contain other types as members.

  • Both have members, which can include constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
  • Members of both can have individualized access levels. For example, one member can be declared Public and another Private.
  • Both can implement interfaces.
  • Both can have shared constructors, with or without parameters.
  • Both can expose a default property, provided that property takes at least one parameter.
  • Both can declare and raise events, and both can declare delegates.

Differences:

The Main difference between reference types (Class) and value types (Struct) we will consider is that reference types are allocated on the heap and garbage-collected, whereas value types are allocated either on the stack or inline in containing types and deallocated when the stack unwinds or when their containing type gets deallocated.

  • Structures are value types; classes are reference types. A variable of a structure type contains the structure’s data, rather than containing a reference to the data as a class type does.

  • Structures use stack allocation; classes use heap allocation.
  • All structure elements are Public by default; class variables and constants are byPrivate default, while other class members are byPublic default.
  • A structure must have at least one nonshared variable or nonshared, noncustom event element; a class can be completely empty.
  • Structure elements cannot be declared as Protected; class members can.

  • Structures are not inheritable; classes are.

  • A structure does not require a constructor; a class does.

 

Q2. Difference between Static Class and Singleton.

Both can be invoked without instantiation, both provide only one “Instance” and neither of them is thread-safe.

static class is basically the same as a non-static class, but there is one difference: a static class contains only static members and a private constructor and cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. The design style embodied in a static class is purely procedural.

Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.

 

Q3. What is the use of Virtual keyword?

The ‘virtual’ keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. By default, methods are non-virtual and you cannot override a non-virtual method. You cannot use the virtual modifier with the staticabstractprivate, or overridemodifiers.

For example, this method can be overridden by any class that inherits it:

public virtual double Area()   
{  
    return x * y;  
}  

 

Q4. What is Abstract Class? Difference between Abstract Class and interface.

An abstract class is a special kind of class that cannot be instantiated. An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated.

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature Interface Abstract class
  Multiple inheritances A class may inherit several interfaces. A class may inherit only one abstract class.
  Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
  Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
  Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.

 

Q5. What is Serialization and De-Serialization?

Serialization:

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

Serialization Graphic

The object is serialized to a stream, which carries not just the data, but information about the object’s type, such as its version, culture, and assembly name. From that stream, it can be stored in a database, a file, or memory.

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange.

Deserialization:

As the name suggests, deserialization is the reverse process of serialization. It is the process of getting back the serialized object so that it can be loaded into memory. It resurrects the state of the object by setting properties, fields etc.

Types of serialization:

  1. Binary Serialization
  2. XML Serialization
  3. JSON Serialization

 

Q6. What’s the difference between a method and a function?

function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:

  1. A method is implicitly passed the object on which it was called.
  2. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class – the class is the definition, the object is an instance of that data).

 

Q6. What do you mean by Generic Function or Generic Class?

Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on. Operations such as adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored.

Generic functions are similarly those which describe the algorithm without specifying a particular data type.



Sanket Prabhu

About Sanket Prabhu

Sanket Prabhu is Technology Evangelist in XR (MR/AR/VR), Unity3D technology, a software engineer specializing in Unity 3D, Extended Reality (MR/AR/VR) application and game development. Currently working as a technology evangelist at Mobiliya, India. He runs a website (arreverie.com) which is the online blog and technical consultancy. The main goal of ARReverie is to develop complete open source AR SDK (ARToolKit+)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 thoughts on “Prepare for an Unity 3D (Game Developer / AR, VR Developer) Interview