How do I optimize my code?,How do I optimize my script?
I'm pretty new to c# and I'm pretty clueless on how to optimize my code in terms of performance and down the road storage and smoothness. I learn best with experimenting with new bits of code.
My controller code so far:
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.SceneManagement;
 
 public class Control : MonoBehaviour {
     
     public float speed;
     public Rigidbody rb;
     public Vector3 jumper;
     protected Collider coll;
     public AudioSource music;
     public AudioSource died;//Create AudioSources
     public AudioSource collect;
     
     
     private float count; //Declare count variable
     
     // Use this for initialization
     void Start () {
     
     AudioSource[] audios = GetComponents<AudioSource>(); //Assign array the name audios
     rb = GetComponent<Rigidbody>();//Assigning the component to the definition 
     coll = GetComponent<Collider>();
     music = audios[0];
     died = audios[1]; //Determine where in the array "audios" this resides, second space here
     collect = audios[2];
     count = 0f; //Set the amount of count
 
     }
                  //the bool must be called as a function, not as a true/false
     bool grounded(){
                         //(origin, direction, range)
         return Physics.Raycast(transform.position, Vector3.down, coll.bounds.extents.y + 0.35f);
            
     }
     
     
     // Update is called once per frame
     void Update () {
         
         if (Input.GetKey(KeyCode.RightArrow) && Input.GetKey(KeyCode.UpArrow))
             transform.Translate(1f*Time.deltaTime*speed,0f,0.5f*Time.deltaTime*speed);
         if (Input.GetKey(KeyCode.RightArrow) && Input.GetKey(KeyCode.DownArrow))
             transform.Translate(1f*Time.deltaTime*speed,0f,-0.5f*Time.deltaTime*speed);        
         if (Input.GetKey(KeyCode.RightArrow) && !Input.GetKey(KeyCode.UpArrow)
             && !Input.GetKey(KeyCode.DownArrow))
 /*Right*/   transform.Translate(1f*Time.deltaTime*speed,0f,0f);
             
 
             
 /*left*/if (Input.GetKey(KeyCode.LeftArrow)  && !Input.GetKey(KeyCode.UpArrow)
             && !Input.GetKey(KeyCode.DownArrow))
             transform.Translate(-1f*Time.deltaTime*speed,0f,0f);
         if (Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.DownArrow))
             transform.Translate(-1f*Time.deltaTime*speed,0f,-0.5f*Time.deltaTime*speed);        
         if (Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.UpArrow))
             transform.Translate(-1f*Time.deltaTime*speed,0f,0.5f*Time.deltaTime*speed);
         
         
         
         
         if (Input.GetKey(KeyCode.UpArrow) && !Input.GetKey(KeyCode.RightArrow)
             && !Input.GetKey(KeyCode.LeftArrow))
             transform.Translate(0f,0f,1f*Time.deltaTime*speed);
         
         if (Input.GetKey(KeyCode.DownArrow) && !Input.GetKey(KeyCode.RightArrow)
             && !Input.GetKey(KeyCode.LeftArrow))
         transform.Translate(0f,0f,-1f*Time.deltaTime*speed);
         
         if(grounded()){
             if(Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.D))
                 rb.velocity = jumper;
             
         }    
         
     }    
        
     void youDead(){
         SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
     }
     
     void nextLevel(){
         SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1f);
     }
         
         
      void OnTriggerEnter(Collider other) 
     {   
         if (other.tag == "Death"){
             died.Play();            
             rb.velocity = jumper;
             Invoke ("youDead", .4f);
         }
         if (other.tag == "Teleporter"){
             transform.position = new Vector3(0f,13.5f,-9f);
             music.Play();
         }
         if (other.tag == "Finish")
             Invoke("nextLevel");
         
         if (other.tag == "Finish2" && count >= 2f)
             Invoke("nextLevel");
             
         
         if (other.tag == "Collectable"){
             other.gameObject.SetActive(false);
             collect.Play();
             count = count + 1f; //When you collide with a collectable count goes up 1
         }
     }
 
 }
 
void OnTriggerEnter(Collider other)
  {   
      if (other.tag == "Death"){
          died.Play();            
          rb.velocity = jumper;
          Invoke ("youDead", .4f);
      }
     else  if (other.tag == "Teleporter"){
          transform.position = new Vector3(0f,13.5f,-9f);
          music.Play();
      }
     else  if (other.tag == "Finish")
          Invoke("nextLevel");
      
      else if (other.tag == "Finish2" && count >= 2f)
          Invoke("nextLevel");
          
      
     else  if (other.tag == "Collectable"){
          other.gameObject.SetActive(false);
          collect.Play();
          count = count + 1f; //When you collide with a collectable count goes up 1
      }
  }
it's better than using lots of ifs :)
Go through your code. Whenever you see some code that repeats more than once, make it a function to reduce code size and make it more readable. You are checking other.tag very frequently! Use "Switch" ins$$anonymous$$d of a chain of "If" statements, like so:
 switch (other.tag)
 {
 case "Death":
 died.Play();            
 rb.velocity = jumper;
 Invoke ("youDead", .4f);
 break;
 
 case "Teleporter":
 transform.position = new Vector3(0f,13.5f,-9f);
 music.Play();
 break;
 
 case "Finish": 
 Invoke("nextLevel"); 
 break;
 
 //keep doing that with your other conditions
 }
Use the least amount of comments possible. When code is changed, comments are a lie waiting to happen. Use "++" ins$$anonymous$$d of "+= 1" for the sake of readability.
Answer by Hellium · Feb 06, 2018 at 12:34 PM
There are many things to be changed IMHO.
First, you should have at least three classes :
- Control : Responsible for moving the character 
- Player : Responsible for the interactions with environment 
- GameController : Responsible for handling score and scene loadings 
Yes, it's more complicated, but it's better to have multiple small scripts doing few things instead of a big one doing a lot of unrelated things.
 using UnityEngine;
 using UnityEngine.SceneManagement;
 using System;
 
 public class Control : MonoBehaviour
 {
     [Header("Components")]
 
     [SerializeField]
     private Rigidbody rb; // Drag & drop the component in the inspector
 
     [SerializeField]
     private Collider coll; // Drag & drop the component in the inspector
     
     [Header( "Attributes" )]
 
     [SerializeField]
     private float speed;
 
     [SerializeField]
     private Vector3 jumper;
     
     private Vector3 velocity;
 
     private bool jumpTrigger;
 
 
     bool IsGrounded
     {
         //(origin, direction, range)
         get { return Physics.Raycast( transform.position, Vector3.down, coll.bounds.extents.y + 0.35f ); }
 
     }
 
     private void Awake()
     {
         enabled = true;
     }
 
     // Update is called once per frame
     void Update()
     {
         Vector3 deltaPosition = Vector3.zero;
 
         if ( Input.GetKey( KeyCode.RightArrow ) )
             deltaPosition.x = 1f;
         else if ( Input.GetKey( KeyCode.LeftArrow ) )
             deltaPosition.x = -1f;
 
         if ( Input.GetKey( KeyCode.UpArrow ) )
             deltaPosition.z = deltaPosition.x > 0 ? 0.5f : 1;
         else if ( Input.GetKey( KeyCode.DownArrow ) )
             deltaPosition.z = deltaPosition.x > 0 ? -0.5f : -1;
 
         transform.Translate( deltaPosition );
 
         if ( Input.GetKeyDown( KeyCode.Space ) || Input.GetKeyDown( KeyCode.D ) )
             jumpTrigger = true;
     }
 
     private void FixedUpdate()
     {
         if ( IsGrounded && jumpTrigger )
         {
             jumpTrigger = false;
             rb.velocity = jumper;
         }
     }
 
     public void Stop()
     {
         rb.velocity = jumper;
         enabled = false;
     }
 }
 using UnityEngine;
 using UnityEngine.SceneManagement;
 using System;
 
 [RequireComponent(typeof(Control))]
 public class Player : MonoBehaviour
 {
     [Header("Components")]
 
     [SerializeField]
     private AudioSource audioSource;  // Drag & drop the component in the inspector
 
     [SerializeField]
     private Control controls;  // Drag & drop the component in the inspector
 
     [Header("Audio clips")]
 
     [SerializeField]
     private AudioClip deathClip; // Drag & drop the clip in the inspector
 
     [SerializeField]
     private AudioClip collectClip; // Drag & drop the clip in the inspector
 
     [Header( "Events" )]
 
     [SerializeField]
     // Drag & Drop in the inspector :
     // 1. The gameobject holding the Control script, and select the "Stop" function
     // 2. The gameobject holding the GameManager script, and select the "RestartLevel" function
     private UnityEngine.Events.UnityEvent onDeath;
 
     [SerializeField]
     // Drag & Drop in the inspector the gameobject holding the GameManager script, and select the "LoadNextLevel" function
     private UnityEngine.Events.UnityEvent onFinishReached;
 
     [SerializeField]
     // Drag & Drop in the inspector the gameobject holding the GameManager script, and select the "IncreaseScore" function
     private UnityEngine.Events.UnityEvent onItemCollected;
     
     [Header( "Other" )]
 
     [SerializeField]
     private GameController gameController; // Drag & drop the gameobject holding the GameController in the inspector
     
     [SerializeField]
     private float speed;
 
     /// <summary>
     /// Awake is called when the script instance is being loaded.
     /// </summary>
     private void Awake()
     {
         if ( audioSource == null )
             audioSource = GetComponent<AudioSource>();
         if ( audioSource == null )
             audioSource = gameObject.AddComponent<AudioSource>();
     }
 
     /// <summary>
     /// Kills the player.
     /// </summary>
     public void Kill()
     {
         audioSource.PlayOneShot( deathClip );
         
         if ( onDeath != null )
             onDeath.Invoke();
     }
 
 
     void OnTriggerEnter( Collider other )
     {
         if ( other.CompareTag( "Finish" ) )
         {
             if ( onFinishReached != null )
                 onFinishReached.Invoke();
         }
         else if ( other.CompareTag("Finish2") && gameController.Score >= 2f )
         {
             if ( onFinishReached != null )
                 onFinishReached.Invoke();
         }
         else if ( other.CompareTag( "Collectable" ) )
         {
             other.gameObject.SetActive( false );
             audioSource.PlayOneShot( collectClip );
             if ( onItemCollected != null )
                 onItemCollected.Invoke();
         }
     }
 }
 using UnityEngine;
 using UnityEngine.SceneManagement;
 
 public class GameController : MonoBehaviour
 {
     private int score;
 
     [SerializeField]
     private UnityEngine.UI.Text scoreText ;  // Drag & drop the text in the inspector
 
 
     public int Score
     {
         get { return score; }
         private set { score = value; scoreText.text = score.ToString(); }
     }
 
     public void ReloadLevel()
     {
         SceneManager.LoadScene( SceneManager.GetActiveScene().buildIndex );
     }
 
     void LoadNextLevel()
     {
         SceneManager.LoadScene( SceneManager.GetActiveScene().buildIndex + 1 );
     }
 
     public void IncreaseScore()
     {
         Score += 1;
     }
 }
Your answer
 
 
             Follow this Question
Related Questions
How do i render a Mesh loop? 1 Answer
Moving an object in a curve along the z-axis 0 Answers
How to fix snake behavior in Unity3d? 0 Answers
Make a 3D Object look like hes facing a point in an 2D space 0 Answers
Hiding part of mesh 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                