Unity Developers Question: Download Unity 3D Developer PDF

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.

Tweet Share WhatsApp

Answer:

No. Texture and Meshes are examples of elements stored in GPU memory and Unity doesn't allow other threads, besides the main one, to make modifications on these kinds of data.
No. Fetching the Transform reference isn't thread safe in Unity.
When using threads, we must avoid using native Unity structures like the Mathf and Random classes:
class RandomGenerator : MonoBehaviour
{
public float[] randomList;

void Start()
{
randomList = new float[1000000];
Thread t = new Thread(delegate()
{
while(true)
{
Generate();
Thread.Sleep(16); // trigger the loop to run roughly every 60th of a second
}
});
t.Start();
}

void Generate()
{
System.Random rnd = new System.Random();
for(int i=0;i<randomList.Length;i++) randomList[i] = (float)rnd.NextDouble();
}
}

Download Unity 3D Developer PDF Read All 27 Unity 3D Developer Questions
Previous QuestionNext Question
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;
}
}
Consider the following code snippet below:

class Mover : MonoBehaviour
{
Vector3 target;
float speed;

void Update()
{

}
}
Finish this code so the GameObject containing this script moves with constant speed towards target, and stop moving once it reaches 1.0, or less, units of distance?