Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by haiwin92 · Feb 06, 2018 at 08:47 AM · c#unity 53doptimization

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
         }
     }
 
 }
 
Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image PersianKiller · Feb 06, 2018 at 11:00 AM -1
Share

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 :)

avatar image Bip901 · Feb 07, 2018 at 02:18 PM 0
Share

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.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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 :

  1. Control : Responsible for moving the character

  2. Player : Responsible for the interactions with environment

  3. 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;
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

517 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges