Unity Developers Question:
Download Questions PDF

Explain the issue with the code below and provide an alternative implementation that would correct the problem.

using UnityEngine;
using System.Collections;

public class TEST : MonoBehaviour {
void Start () {
transform.position.x = 10;
}
}

Answer:

The issue is that you can't modify the position from a transform directly. This is because the position is actually a property (not a field). Therefore, when a getter is called, it invokes a method which returns a Vector3 copy which it places into the stack.

So basically what you are doing in the code above is assigning a member of the struct a value that is in the stack and that is later removed.

Instead, the proper solution is to replace the whole property; e.g.:

using UnityEngine;
using System.Collections;

public class TEST : MonoBehaviour {
void Start () {
Vector3 newPos = new Vector3(10, transform.position.y, transform.position.z);
transform.position = newPos;
}
}

Download Unity 3D Developer Interview Questions And Answers PDF

Previous QuestionNext Question
Unity3D Developer Interview Questions:Can threads be used to modify a Texture on runtime?
Can threads be used to move a GameObject on the scene?
Consider the snippet below:
class RandomGenerator : MonoBehaviour
{
public float[] randomList;

void Start()
{
randomList = new float[1000000];
}

void Generate()
{
System.Random rnd = new System.Random();
for(int i=0;i<randomList.Length;i++) randomList[i] = (float)rnd.NextDouble();
}
}
Improve this code using threads, so the 1000000 random number generation runs without spoiling performance.