- Home /
Want to optimize this code. causes a wired issue
This code is called when click on "A button". When i click on this button:: on editor: run smoothly (no any issues). on build: it causes a not responding at every first click on the button, and sometimes it stops the game.
when im trying to check what causes that, i found that code...
notice: this code does not give any errors and works perfectly like i want. notice: this code in a function.
GameData data = SaveSystem.Load();
int l = 0;
int mapId = 1;
for(int i = 0; i < maps_contents.Length; i++) {
Debug.Log("I:" + i);
for(int k = 0; k < maps_contents[i].transform.childCount; k++) {
Debug.Log("K:" + k);
GameObject child = maps_contents[i].transform.GetChild(k).gameObject;
child.GetComponent<Button>().interactable = false;
GameObject ImgChld = child.transform.GetChild(0).gameObject;
GameObject TextChld = child.transform.GetChild(1).gameObject;
Color TmpClr = ImgChld.GetComponent<Image>().color;
TmpClr.a = 0.6f;
ImgChld.GetComponent<Image>().color = TmpClr;
TextChld.GetComponent<Text>().text = mapId.ToString();
if(data.map != null && data.map > 0) {
for(int j = l; j < data.map; j++) {
Debug.Log("J:" + j);
child.GetComponent<Button>().interactable = true;
TmpClr.a = 1f;
ImgChld.GetComponent<Image>().color = TmpClr;
}
}
Debug.Log("L:" + l);
l++;
mapId++;
}
}
Answer by revolute · Sep 11, 2019 at 01:25 AM
If this code is really what is going into your build, then the first job should be removing redundant Debug.Log calls. They cause a bit of hiccups and you call them for i k j^2 times in a frame. If you really wish to keep a track, I would recommend using stringbuilder to create a log string and print it out at the end of the function.
Next would be cleaning up more logic. For instance, ImgChld.GetComponent() gets called multiple times without doing anything with the loop for j . After the block if(data.map != null && data.map > 0)
, looping for j is irrelevant since the variable "child", "ImgChld" never changes, assigned values are the same.
Last would be caching where necessary. ImgChld.GetComponent() gets called a few times for the same block. Caching it by ImgChldImg = ImgChld.GetComponent<Image>();
(or whatever you wish to call this variable) and then calling the latter get and set color variables via ImgChldImg.color = TmpClr
would give you better performance.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# coding help 1 Answer
Raycast Targeting issue 1 Answer
One big script or lots of small ones? 0 Answers