- Home /
how to achieve faster code execution in unity?
hello.
before i start;
-using visual studio to write code
writing codes in c#
using unity to develope games/apps
so i was working on a project. using unity 4.++
then i decided to upgrade to 2019 version.(am using free version)
in the previous version .. my games are able to run without any issue;
after upgrading.. when i tried to run my game(in editor) i got some error. after checking i found out that
some codes are being executed rather slow. i will explain what i mean.
code example;
public class AAA : scriptableobject
public string name;
public string d;
public string f;
public string j;
public string g;
etc..
prefab
public class BBB : monobehaviours // this is attached to prefab
public string name;
private string b;
private string c;
private string d;
public void setup( AAA aaa)
{
name = aaa.name;
b = aaa.d;
etc etc
/// just assigning value to the variables above from AAA
}
public class CCC : monobehaviour
list<AAA> object = new list<AAA>() { about 100 items in here };
void start()
{
foreach (AAA aaa in object)
{
var newobject = (instantiate prefab , here i use resourcesload)
newobject.GetComponent<BBB>().setup(aaa);
// im using debuglog to show the error just as example
Debug.log(newobject.getcomponent<BBB>().name);
*****where error null reference exception occur
}
}
so, i have come to conclusion that the error are caused by lags in code execution because the error
are not constant. sometimes after 10 loops, sometimes 11, sometimes 7 etc and also
tried the exact code (if i may, the whole game scripts) on both version of unity, only the 2019 gives the error
my questions now are;
is there some kind of settings in 2019 versions that might have caused this? or
if its a bug, is there anyway to fix
thank you:)
Answer by FlaSh-G · May 09, 2020 at 05:01 AM
Code execution speed does not have anything to do with errors being or not being thrown unless you do threading stuff, which you don't. Unless you're using Unity's jobs system or explicitly use threads or tasks (and you do neither in that code), Unity's execution of your code is strictly single-threaded, which means that one line of code is executed after the next.
Of course, there's some exceptions to that exact wording, like pauses in coroutine code or Unity's async methods, but - and that's the summary - if you have a regular foreach loop in a regular method, whatever your error is, it's got nothing to do with speed. The order in which certain things happen might be undefined (like which object gets Start() called first when they're both in the scene from the beginning), but the code still runs single-threaded. So there is no other code racing your code for faster completion. That's simply not how regular code (or properly written multi-threaded code) works.
So when you have an issue like this, you have to find the mistake in the code, not fiddle with code execution speed.
And regarding that, I honestly can't find anything out of the ordinary in your code that might cause irregular exception throws. So I'd recommend building a minimal example script that doesn't do much except the stuff that you observe the bad behavior in. Try to narrow the code down to what actually causes the error and fix it.
hi. thanks for the reply.
well, all the points you made were exactly as i thought it to be.
and as you said, i did made $$anonymous$$imal example script to simulate the error. the example script i gave is the example script.
as an addition.. i also did a break point and stepping in line by line on the foreach loop. it goes normally as it should be. but gave error on runtime.
this is how my thought process;
since my actual scripts does not involve any kind of time dependence methods(coroutine, invoke etc). it should run as single thread.
from the script above, i got a null reference exception which most likely pointing out to the instantiating process of my prefab.
thats why i radically come to conclusion that it might somehow affected by other factor. i came to think about speed because of the irregularities nature or the error. might be bug?
because at least error in code will give a regular error.
as for now, i am sure my actual codes doesnt have any problem because the exact same codes works in other unity version. (both my actual script and the example script)
tested several times on different unity versions, the error only happens when i use Unity 2019.3.13.
i have switch to latest unity 2018(LTS) and everything works fine now.
am still open to any insight on why this behaviour happened tho. so anyone is welcome to add:)
since my actual scripts does not involve any kind of time dependence methods(coroutine, invoke etc). it should run as single thread.
Since it's a massive trap to fall into, I just want to make sure and say that coroutines and the invoke methods are all on the main thread with no multithreading involved.
tested several times on different unity versions, the error only happens when i use Unity 2019.3.13.
i have switch to latest unity 2018(LTS) and everything works fine now.
Woof, that sounds heavy. If you're able to make an example project for reproduction, submitting a bug report with this is probably a very good idea.
hi. thanks for the suggestion. ive already sent a report btw. but did not provide an example project tho.
"(...) errors are not constant. sometimes after 10 loops, sometimes 11, sometimes 7 etc" (as @FlaSh-G mentioned) In Unity there is this specific variations of race condition error as a result of how $$anonymous$$onobehaviours are called in the scene ie.: one can't always be 100% sure which Awake/etc is called first so initialization, or program execution flow in general, can become compromised by changes in (single-threaded) execution order (for very badly/brittle-written code this can be triggered by even scene being edited in extreme cases). $$anonymous$$y bet is that upgrading from 4.x to 2019 broke some obscure rule that made your code not throw exceptions before. If that's the case then fixing it should be rather straight forward - once you figure out dependencies this scripts has.
I currently don't see potential for this in the posted code, but that's a very good point.
thanks for the reply. @andrew-lukasik
good point btw and i am aware of this.
As @FlaSh-G mentioned i did not really see how it can cause the error for the codes posted above.
as only 1 monobehaviour is calling start function. (i assume all fields serialization takes place before start - correct me if im wrong).
Yeah, deserialization happens during Instantiate (or during scene initialization). Then Awake is called, followed by OnEnable (if the prefab was active and the prefab component enabled). Then, the code after the Instantiate call continues, and Start is being run in a batch with other fresh objects at the end of the frame.
If I were you I would add bunch of assertions just after instantiate line to make sure objects are being loaded, instantiated and also those instance contain components &| data you expect them to have.
Answer by logicandchaos · May 13, 2020 at 02:12 AM
You have to set up code execution correctly, if you get an error something is null ref in start then you need to to fill that reference in an awake call. If you set things up right you won't get these errors. EDIT: Hey sorry it sounded like a race condition issue, but after reading the comments and checking through the code I see that is not the case, I'm not sure what is the issue, but wouldn't it be easier to just have a reference to the scriptableObject?
hi. thanks for the reply.
the reference to the scriptableobject is in object in class C. i used resources load. in the example code above its only only 2 kind of scriptable object and pasted it to 100. (just for simplicity). i could reference it from the inspector but i dont think it will make difference about the error.
Your answer
![](https://koobas.hobune.stream/wayback/20220612233720im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Monodevelop 4.0.1 lags 0 Answers
Smooth movement of simple GameObject on Android 1 Answer
complexity of hierarchy affects performance? 1 Answer
Performance issue Unity 2D 2 Answers
Editor lags after update 0 Answers