Answers

Question and Answer:

  Home  Unity 3D Developer

⟩ 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.

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();

}

}

 226 views

More Questions for you: