Is void Start () { } required to be in the script if you are not using it? If not, can I delete it?
Im cleaning out my scripts of trash to make them as lean as possible.
Here is my entire script which works perfectly fine controlling the max v of my ball:
public class Ball : MonoBehaviour {
public float xMaxV = 10f;
public float yMaxV = 10f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
var rb = GetComponent<Rigidbody2D> ();
Vector3 vel = rb.velocity;
rb.velocity = new Vector3 (Mathf.Clamp(vel.x, -(xMaxV), xMaxV), Mathf.Clamp(vel.y, -(yMaxV), yMaxV), Mathf.Clamp(vel.z, 0f, 10f));
}
}
Next time youâre in doubt just experiment. If something breaks youâll learn why and what not to do, if it doesnât break youâre probably good to go
In fact, to help you stay clean, go to where you downloaded unity and edit the script template to your desire.
For exampleâŚ
C:\Program Files\Unity\Editor\Data\Resources\ScriptTemplates
There you should see all the script templates when making a new script in unity. The C# one should be called
â81-C# Script-NewBehaviourScript.cs.txtâ. The default adds Update and Start. I edited it so they are removed, I also removed the âusing system.collectionsâ and set up the whitespacing as desired.
+1 to what DuffyT said.
Remember that Update function is called several times per second and except you are doing some magic, it will be good idea / practice to retrieve the component only once⌠and the Start method it is the right place.
Just wanted to say thanks for this. Really useful for me. I added system.collections.generic to mine, since Iâm using lists a lot on my current project. Iâll keep a note on this so I can use it in later games
Start is called before the first frame that an object is active. So, Activate Object>Start>Update Each Frame
Start is typically used for initialization, like storing components or values, or initializing values. Update is used to make changes to those values or any other values
Killing start will buy you almost nothing in terms of performance. Itâs still worth doing for clean code. To optimise this script you want to kill the GetComponent inside Update.
That said there is nothing in this script that will tax even the most ancient of devices.
Very true, but itâs still good practice to start doing it that way for the future. I have over 50 classes in my current project that require some sort of caching (some alot more than others) and I canât image what it would do to performance if they all constantly got and âre-gotâ their components in update.