- Home /
Best Unity Practices
Hi everyone,
This is a very general question that i am going to pose to everyone in unity answers.
What are the best practices in getting the most efficient code output for the cheapest amount of processing, when writing javascript code in unity?
I ask this question for many reasons, but mainly for beginners like myself. I want to learn unity the best way with a good cognitive logical structure. Personally i do not like trial and error learning because you can pick up bad habits that can create code inefficiencies. I am a university student, and i have learnt java and javascript before, but the way unity works especially with the different update methods confuses, because i am not dealing with static objects mostly as the page updates every x amount of frames per second.
I recently learnt that you should never write a "GameObject.Find("String")" in the update, it is better to do GameObject.Find(String) (no quotes), and that when retrieveing specific componants from an object do this:
var controller:GameObject;
**private var getEssenceHandlerComponant:GetEssenceHandler;**
private var valueGuiText:GUIText;
function Start() {
**getEssenceHandlerComponant = controller.GetComponent(GetEssenceHandler);**
valueGuiText = GameObject.Find("Value").guiText;
}
Instead of this:
public var controller:GameObject;
**var getEssenceHandlerComponant:Component = controller.GetComponent("GetEssenceHandler");**
function LateUpdate () {
var number:float = getEssenceHandlerComponant.lifeEssenceCarrier;
number = Mathf.Floor(number);
gameObject.Find("Value").guiText.text = number.ToString() + "%";
}
But anyways those are just examples of better ways of doing the same thing for the cheaper price. Please do not hesitate to give some advice guys. We are all here to help each other in the end. :)
Thanks in advance
Answer by hijinxbassist · Mar 29, 2012 at 09:23 AM
Here is a good place to start http://unity3d.com/support/documentation/ScriptReference/index.Performance_Optimization.html>Performance Optimization. There is a full discussion with examples http://unity3d.com/support/resources/unite-presentations/performance-optimization.html> here.
Type all vars to avoid any dynamic typing. Using strict typing is a good way to slim down. #pragma strict.
var color=Color.green;
var color:Color=Color.green;
Avoid calling things from Strings if at all possible. Avoid Array(), and use []
var array:Array=new Array();//creates empty array
var colorArray:Color[]=new Color[5];//creates a color array with 5 empty slots
Avoid Update calls wherever you can, including similar constantly updating functions...OnGUI(),FixedUpdate(),LateUpdate()
Best thing is structure, avoid redundancy and unnecessary calls.
Your answer
Follow this Question
Related Questions
press e to speek -1 Answers
Add force to GameObject 2 Answers
enable and disable boxcollider (whats wrong with my script?) 2 Answers
How do I reset a variable? 2 Answers