EzDevInfo.com

unity3d interview questions

Top unity3d frequently asked interview questions

How to prepare a Unity project for git?

What are the steps necessary to prepare a Unity project for committing to a git repository eg. github? I don't want to store unnecessary files (specially temp files and avoid binary formats as much as possible).


Source: (StackOverflow)

How to use Git for Unity source control?

What are best practices for using Git source control with Unity, particularly in dealing with the binary nature of Unity projects? Please describe the workflow, what paths would be included in .gitignore, what settings should be set in Unity and/or the project, and any other special things that should be noted.

Note: I realize that using the Asset Server is the Unity-recommended way, but I would like to use Git for a variety of reasons. Please no answers that state or argue that I should just use the Asset Server. The Asset Server really isn't an option for me.


Source: (StackOverflow)

Advertisements

How does StartCoroutine / yield return pattern really work in Unity?

I'm new to Unity and C#. I understand the principle of coroutines (mainly from iterators in Python). I can also get the standard StartCoroutine / yield return pattern to work in C# in Unity, e.g. invoke a method returning IEnumerator via StartCoroutine and in that method do something, do yield return new WaitForSeconds(1); to wait a second, then do something else.

My question is: what's really going on behind the scenes? What does StartCoroutine really do? What IEnumerator is WaitForSeconds returning? How does StartCoroutine return control to the "something else" part of the called method? How does all this interact with Unity's concurrency model (where lots of things are going on at the same time without use of coroutines)?


Source: (StackOverflow)

How to write a GUI editor for Graph or Tree structures

Unity3D's Mecanim animations system has a custom EditorWindow that allows to define a tree (a blend tree in this case) thorough GUI.

It looks like:

enter image description here

It offers the possibility of creating nodes (states) and connect them (transitions).

Now, I'm developing some graph and and tree structure and I would like to write an editor extension in order to allow my game designer to populate those structures.

I want pretty most recreate exactly an EditorWindow like the one of Mecanim animator (figure above).

My question is: are there any available components that I can use for such a task? Is there any builtin class used for the drawing and connecting boxes and arrow? Or I need to write completely the GUI elements by my own?


Source: (StackOverflow)

Unable to verify assembly data; you must provide an authorization key when loading this assembly

I'm testing the InteractiveConsole example in Unity. I did some configurations as described in the official tutorial. After some setups I got on step 7: Run our example code.

However, I'm receiving the following errors:

Unable to verify assembly data; you must provide an authorization key when loading this assembly. UnityEngine.Security:LoadAndVerifyAssembly(Byte[]) c__Iterator1:MoveNext() (at Assets/Facebook/Scripts/FB.cs:326)

Could not securely load assembly from https://integrated-plugin-canvas-rsrc.fbsbx.com/rsrc/unity/lib/sdk_4.0/CanvasFacebook.dll UnityEngine.Debug:LogError(Object) FbDebug:Error(String) c__Iterator1:MoveNext() (at Assets/Facebook/Scripts/FB.cs:329)

Not sure what to do. Any ideas?


Source: (StackOverflow)

Unity Android Build Error WIN32 Exception ZipAlign

Every time I try to build my game for android, I get this error:

Error building Player: Win32Exception: 
ApplicationName='.../.../.../.../adt-bundle-mac-x86_64-20140624/sdk/tools/zipalign',
CommandLine='4"/.../.../.../.../Asteroid2(2)/Temp/StagingArea/Package.apk'". 
CurrentDirectory='Temp/StagingArea'

Any ideas? I'm stumped. I've redownloaded the SDK and that didn't help.


Source: (StackOverflow)

Android and Unity 3D game development

I am starting to explore the game development using unity 3d for android. I have downloaded the trial version of unity 3.3. I went through few tutorials.

I have one question that is not answered. In the normal apps which we develop using eclipse, we can deploy onto mobile by copying the apk file. What about unity 3d? How do I get the game onto my phone. I don't want to publish on market.


Source: (StackOverflow)

Weird collision bug in Unity 2d game

Github Repository (Scripts folder, has all code in .cs files)

I have this weird collision bug in unity, here's a gif of it:

GIF

Recreating: In the gif, for example, I press both Left arrow and Up arrow until the velocity normalizes, and I get some why stuck in a block.

I've had this before with my own collision algorithm when I did the game in XNA, hoped this would not happen in Unity.

This is the player script PlayerMovement:

using UnityEngine;
using UnityEngine.UI;

namespace Assets.Scripts
{
    public enum Directions
    {
        Back,
        Left,
        Front,
        Right,
        Idle = -1
    }

    public class PlayerMovement : MonoBehaviour
    {
        #region Public Members

        /// <summary>
        /// Maximum speed of the player (Accelerated to over a period of time)
        /// </summary>
        public float speed;

        /// <summary>
        /// Debug UI.Text element
        /// </summary>
        public Text debugText;

        #endregion

        #region Constants

        /// <summary>
        /// Constant for decaying the velocity on updates
        /// </summary>
        private const float VELOCITY_DECAY_FACTOR = 0.85f;

        /// <summary>
        /// Constant to convert normal speed sizes to fit the scale
        /// Of UnityEngine.Vector2
        /// </summary>
        private const float HUMAN_TO_VECTOR_SCALE_FACTOR = 850f;

        /// <summary>
        /// Constant to set the base speed of the player animation
        /// </summary>
        private const float BASE_ANIM_SPEED = 0.7f;

        /// <summary>
        /// Constant to slightly reduce the animation speed after 
        /// It is multiplied by the velocity of the player
        /// </summary>
        private const float POST_VELOCITY_MULTIPLICATION_ANIM_SPEED_FACTOR = 0.5f;

        /// <summary>
        /// Constant to set the animation speed
        /// </summary>
        private const float ANIM_SPEED_MODIFIER = BASE_ANIM_SPEED * POST_VELOCITY_MULTIPLICATION_ANIM_SPEED_FACTOR;

        /// <summary>
        /// Epsilon before velocity zerofication
        /// </summary>
        private const float VELOCITY_EPSILON = 0.1f;

        #endregion

        #region Private Members

        private Rigidbody2D rb2D;
        private Vector2 velocity;
        private Animator animator;
        private Directions dir = Directions.Idle;

        #endregion

        #region Game Loop Methods

        private void Awake()
        {
            animator = GetComponent<Animator>();
            rb2D = GetComponent<Rigidbody2D>();
        }

        private void FixedUpdate()
        {
            float vertical = Input.GetAxisRaw("Vertical");
            float horizontal = Input.GetAxisRaw("Horizontal");
            UpdateVelocity(horizontal, vertical);
            UpdateAnimation(horizontal, vertical);
            UpdateMovment();
        }

        #endregion

        #region Animation Methods

        private void UpdateAnimation(float horizontal, float vertical)
        {
            UpdateAnimation(new Vector2(horizontal, vertical));
        }

        private void UpdateAnimation(Vector2 input)
        {
            Directions direction;

            if (input.y > 0)
                direction = Directions.Back;
            else if (input.y < 0)
                direction = Directions.Front;
            else if (input.x > 0)
                direction = Directions.Right;
            else if (input.x < 0)
                direction = Directions.Left;
            else
                direction = Directions.Idle;

            SetDirection(direction);
        }

        private void SetDirection(Directions value)
        {
            animator.SetInteger("Direction", (int)value);
            dir = value;
        }

        #endregion

        #region Movement Methods

        private void UpdateMovment()
        {
            rb2D.MovePosition(rb2D.position + velocity * Time.fixedDeltaTime);
            KinematicsDebugPrints();
            ApplySpeedDecay();
        }

        private string GetDebugPrintDetails()
        {
            return string.Format("HOR : {0}\nVER : {1}\nDIR : {2}:{3}\nX : {4}\nY : {5}",
                velocity.x,
                velocity.y,
                animator.GetInteger("Direction").ToString().PadLeft(2),
                (Directions)animator.GetInteger("Direction"),
                rb2D.position.x,
                rb2D.position.y);
        }

        private void KinematicsDebugPrints()
        {
            var details = GetDebugPrintDetails();
            debugText.text = details;
            Debug.Log(details);
        }

        private void UpdateVelocity(float horizontal, float vertical)
        {
            if (vertical != 0)
                velocity.y += Mathf.Sign(vertical) * speed / HUMAN_TO_VECTOR_SCALE_FACTOR;
            if (horizontal != 0)
                velocity.x += Mathf.Sign(horizontal) * speed / HUMAN_TO_VECTOR_SCALE_FACTOR;
            animator.speed = ANIM_SPEED_MODIFIER * velocity.MaxOfXandY() ;
        }

        private void ApplySpeedDecay()
        {
            if (velocity == Vector2.zero) return;

            velocity *= VELOCITY_DECAY_FACTOR;
            velocity = velocity.ZerofiyTinyValues(0.1f);
        }

        #endregion
    }
}

This is the player object currently:

player

And this is the wall object (prefab is the same for all walls except for the image:

WALL

This is a gif of my other bug:

bug two

This is how the collision box and circles look like:

new collision boxes

And this are the details from the inspector

new inspector


So after speaking with Hamza Hasan, he helped me to turn all the outer wall box colliders into four continues colliders, one per side(top, bottom, left, right).

The code for it is on the BoardManager script in the CreateWallsColliders method.

This is how the scene currently looks like in the scene editor:

new scene editor


Source: (StackOverflow)

Unity 4.3 - understanding positions and screen resolution, how to properly set position of object?

Using Unity 4.3 in 2d mode I have a GameObject which is a sprite (in the SpriteRenderer I've setted the sprite), and I'm trying to position it in the top-left of the screen.

I would like to have this sprite to be positioned in the top left (for example) in every resolution (I have iOS as build target so in my case I'm talking about iPhone all resolutions, retina, non-retina, iPad etc).

What I'm missing is how exactly the coordinate system works, I'm used to work with pixels in a coordinate system where 0,0 start from bottom-left or top-left.

Here in Unity 4.3 seems like the 0,0 is in the center (this is not a big problem obviously) but what it makes me confused is that if I print the width of my object (which is 128px) I get an 1.06 as value, and also the screen is subdivided in "points" I suppose, so the left is -3 and the right is +3

so questions are: Why my sprite width is 1.06 ? How I'm supposed to position things perfectly within this system ?

Imagine I want to position a square of 128px*128px exactly at top left, how can I do it?


Source: (StackOverflow)

Debugging with unity

At the current moment, what I'm doing is that I'm opening Unity, double click on one of those scripts I've written, then MonoDevelop gets opened, now I have to close unity and in MonoDevelop I do Run >> Run with >> Unity Debugger.

After this Unity gets opened and when I press the play button in unity the debugging session starts. But once only. If I stop this session in either Unity or MonoDevelop I have to repeat this whole procedure all over again, which is very tedious. I have to open Unity, close Unity, (I have to close it because next step which is Run >> Run with >> Unity Debugger will open unity and if unity is already opened I'm getting error saying that only one instance of unity can open one project at a time).

What I'm asking is:
Is there any better workflow which would free me from this tedious switching on and off Unity, and every time I stop debugging session I would just start normally without doing these tedious repetitions?
Thanks.


Source: (StackOverflow)

Why calling Process.killProcess(Process.myPid()) is a bad idea?

I've read some posts saying using this method is "not good", shouldn't been use, it's not the right way to "close" the application and it's not how android works...

I understand and accept the fact that Android OS knows better then me when it's the right time to terminate the process, but I didn't heard yet a good explanation why it's wrong using the killProcess() method?. After all - it's part of the android API...

what I do know is that calling this method while other threads doing in potential an important work (operations on files, writing to DB, HTTP requests, running services..) can be terminated in the middle, and it's clearly not good. also I know I can benefit from the fact that "re-open" the application will be faster, cause the system maybe still "holds" in memory state from last time been used, and killProcess() prevents that.

Besides this reason, assuming I don't have such operations, and I don't care my application will load from scratch each run, there are other reasons why not using the killProcess() method?

I know about finish() method to close an Activity, so don't write me about that please.. finish() is only for Activity. not to all application, and I think I know exactly why and when to use it...

And another thing - I'm developing also games with the Unity3D framework, and exporting the project to android. When I decompiled the generated apk, I was very suprised to find out that the java source code created from unity - implementing Unity's - Application.quit() method, with Process.killProcess(Process.myPid()).

Application.quit() is suppose to be the right way to close game according to Unity3d guides (is it really? maybe I am wrong, and missed something), so how it happens that the Unity's framework developers which doing a very good work as it seems implemented this in native android to killProcess()?


Source: (StackOverflow)

Building Player Baking Runtime Android Forever Loading

I've been building an Android app on Unity with 3 scenes. The first 2 scenes work perfectly but the last scene was giving me trouble. The game kept crashing on that scene

So while checking out the Unity Forums, they suggested that I copy paste all objects onto a new scene and try and see if it works.

But now that I've done that, I'm not even able to export it. While building player, my loader gets stuck on this: Building Scene 2: Name (10/15 Bake Runtime | 1 jobs)

I've not changed anything else in the settings, and if I remove the 3rd scene, it builds normally. When I only add the 3rd scene it gets stuck on the same.

What could be the problem? enter image description here enter image description here


Source: (StackOverflow)

Asynchronous methods in using statement

Note: I'm using C# in Unity, that means version .NET 3.5, so I cannot use await or async keyword..

What will happen to using statement when I put a method in it which works asynchronously?

using (WebClient wc = new WebClient()) {
    wc.DownloadFileAsync(urlUri, outputFile);
}
SomeMethod1();
SomeMethod2();

As you know, after the method DownloadFileAsync() is called, SomeMethod1() will be called which is out of the using block while DownloadFileAsync() is still working. So now I'm really confused what would happen to the using statement and the asynchronous method in this case.

Would Dispose() of wc be called at the right time without any problems?

If not, how do I correct this example?


Source: (StackOverflow)

What Language is Used To Develop Using Unity

What language does one need to use when programming with Unity? Or is it an API for many languages?

I read through the docs and I guess I missed the point on the language used.

It says it has iOS deployment, would this still allow the programmer to code in objective C?

Is Unity an sdk which can be used for many platforms or how does it work? It mentions deploy the same code on multiple platforms.


Source: (StackOverflow)

Unity in iOS Crashes in Standard Library

I'm trying to bring Unity into an existing iOS app and am having problems. Since Unity wants a very specific build setup, I've created a cocoapod for it. I'm launching Unity from a button press, and I can verify that the initialization process is the same for my cocoapod and a stand-alone Unity export. My cocoapod version crashes with EXC_BAD_ACCESS very early on below this call:

UnityInitApplicationNoGraphics([[[NSBundle mainBundle] bundlePath]UTF8String]);

This is the stacktrace that I get

 #0    0x00b9488c in std::_Rb_tree<int, std::pair<int const, Object::RTTI>, std::_Select1st<std::pair<int const, Object::RTTI> >, std::less<int>, stl_allocator<std::pair<int const, Object::RTTI>, (MemLabelIdentifier)1, 16> >::_M_begin() [inlined] at /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/usr/include/c++/4.2.1/bits/stl_tree.h:476
 #1    0x00b9488c in std::_Rb_tree<int, std::pair<int const, Object::RTTI>, std::_Select1st<std::pair<int const, Object::RTTI> >, std::less<int>, stl_allocator<std::pair<int const, Object::RTTI>, (MemLabelIdentifier)1, 16> >::find(int const&) [inlined] at /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/usr/include/c++/4.2.1/bits/stl_tree.h:1373
 #2    0x00b94874 in std::map<int, Object::RTTI, std::less<int>, stl_allocator<std::pair<int const, Object::RTTI>, (MemLabelIdentifier)1, 16> >::find(int const&) [inlined] at /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/usr/include/c++/4.2.1/bits/stl_map.h:542
 #3    0x00b94874 in Object::ClassIDToRTTI(int) at /Applications/buildAgent/work/d63dfc6385190b60/Runtime/BaseClasses/BaseObject.cpp:828
 #4    0x00b9b88c in Unity::GameObject::RegisterClass() at /Applications/buildAgent/work/d63dfc6385190b60/Runtime/BaseClasses/GameObject.cpp:1374
 #5    0x00b94f48 in Object::InitializeAllClasses() at /Applications/buildAgent/work/d63dfc6385190b60/Runtime/BaseClasses/BaseObject.cpp:903
 #6    0x00cda400 in InitializeEngineNoGraphics() at /Applications/buildAgent/work/d63dfc6385190b60/Runtime/Misc/SaveAndLoadHelper.cpp:210
 #7    0x00ccb594 in PlayerInitEngineNoGraphics(std::string const&, std::string const&) at /Applications/buildAgent/work/d63dfc6385190b60/Runtime/Misc/Player.cpp:711
 #8    0x00ac6170 in UnityInitApplicationNoGraphics at /Applications/buildAgent/work/d63dfc6385190b60/PlatformDependent/iPhonePlayer/LibEntryPoint.mm:188

This tells me that it's crashing down in the Standard Template Library but I can't figure out why. Could it be some kind of a linking mismatch? Here is my podspec file incase I'm missing something there:

Pod::Spec.new do |spec|
  spec.name        = "Games"
  spec.version     = "0.1.0"
  spec.license     = 'Commercial'
  spec.source      = { :git => "GIT_URL", :tag => spec.version.to_s }
  spec.author      = { "CaseyB" => "MyEmail" }
  spec.platform    = :ios, '7.0'

  spec.prefix_header_file = 'Classes/iPhone_target_Prefix.pch'

  spec.header_dir = '..'
  spec.header_mappings_dir = 'Classes'
  spec.source_files = '**/*.{h,m,mm,cpp,dll.s}'
  spec.requires_arc = false

  spec.libraries = 'stdc++', 'iconv.2'

  spec.xcconfig = {
    'GCC_USE_INDIRECT_FUNCTION_CALLS' => 'NO',
    'GCC_THUMB_SUPPORT' => 'NO',
    'CLANG_CXX_LANGUAGE_STANDARD' => 'gnu++0x',
    'CLANG_CXX_LIBRARY' => 'libstdc++',
    'OTHER_LDFLAGS' => '-stdlib=libstdc++ -weak_framework CoreMotion -weak_framework iAd -weak_framework AVFoundation -weak_framework GameKit -weak-lSystem',
    'LIBRARY_SEARCH_PATHS' => '$(PODS_ROOT)/Games/Libraries',
  }

  spec.frameworks = 'Foundation', 'UIKit', 'OpenGLES', 'QuartzCore', 'OpenAL', 'AudioToolbox', 'CFNetwork', 'MediaPlayer', 'CoreLocation', 'SystemConfiguration', 'CoreMedia', 'CoreVideo', 'CoreGraphics', 'CoreBluetooth'

  spec.vendored_library = 'Libraries/*.a'
end

Source: (StackOverflow)