Passing local variables to struct
Hi! i am trying to implement the unity jobs function and as ive read i mus use struct in order to do so. My problem is this, on a controller script i am try to implement the job only for a specific very time consuming function.How can i pass my local variables that many other functions depend on to the struct function? An example of my script is this:
namespace Something
{
public class Controller: MonoBehaviour
{
[...]
public float Friction { get
{
return friction;
}
}
protected float friction = 0; // one of many vars
public struct WhyGod : IJob
{
friction = 0; //i want this to be able to access the variable above
public void Execute(){
Thanks in advance and sorry for my grammar.
Answer by Bunny83 · May 07, 2020 at 11:58 PM
That's completely impossible. Your friction variable is an instance variable so it belongs to a particular instance of that class. Your struct is a seperate type just like a class. So an "instance" of your struct can only access that variable when that struct has a reference to an actual instance of your Controller class.
You could make your variable static so it's not bound to a certain instance. However since your struct implements the IJob interface you probably want to use it in Unity's job system. In that case I would strongly recommend to not do anything like that since jobs are actually executed on seperate threads. So you could easily run into countless unpredictable race conditions.
Unity tries to simplify the usage of multithreading for the user. However knowing the fundamental rules and concepts about multi threading is still required. Otherwise, sooner or later, you will just shoot yourself in the foot.
Note that your code shows something completely different from what you're asking in your description. In your description you talk about reading the value inside your job while in the code you provided you try to write to that value. If you actually just want to read the value I would highly recommend to just add a member variable to your job and initialize it with the value of your friction variable before you start the job. The main point why Unity uses a struct instead of a class is to avoid concurrent data access. That means a job should contain all data it needs so it can actually run in isolation.
Hello! Thanks for taking the time to answer. Is there anything i can do at this point? I really need to implement the job system since i have like 4 controllers in a single scene and my fps get a huge hit.
Your answer
Follow this Question
Related Questions
float value is reset after every update 1 Answer
Use enum hidden value as something other than int? (C#) 2 Answers
Adding to variable only once? 0 Answers
Logical explaination of this code 1 Answer
name a variable when it's created??? 0 Answers