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 /
avatar image
0
Question by noorkaximi · Apr 03, 2018 at 05:42 AM · android buildlagperformance optimization

My script is causing lag

How i can reduce lag. this script is causing lag in my android game can anyone tell me what is wrong with my code

 using GoogleMobileAds.Api;
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.SceneManagement;
 
 public class rabbit_controller : MonoBehaviour
 {
     private bool isGrounded;
     public float gravity;
     static Rigidbody2D rb;
     static Animator  animator;
     bool godMode=false;
     public static bool isDead;
     public static bool win;
      static AudioSource scrmAud;
      static AudioSource winAud;
      static AudioSource failAud;
      bool buttonPressed ;
      Camera main;
      float jumpPower;
     // Use this for initialization
     void Start()
     {
         jumpPower = LevelSettings.rabitJumpPower;
         main = Camera.main;
         isDead = false;
         win = false;
         isGrounded = false;
         buttonPressed = false;
         rb = GetComponent<Rigidbody2D>();
         animator = GetComponent<Animator>();
         scrmAud = GameObject.Find("rabbitScreaming").GetComponent<AudioSource>();
         winAud = GameObject.Find("win_sound").GetComponent<AudioSource>();
         failAud = GameObject.Find("gameover_sound").GetComponent<AudioSource>();
 
       }
   
     // Update is called once per frame
     void FixedUpdate()
     {
         if (win || isDead)
         {
             return;
         }
      
         //For Moving Forward
         float x = transform.position.x;
         x += LevelSettings.rabitSpeed * Time.deltaTime;
         transform.position = new Vector3(Mathf.Lerp(transform.position.x, x, Time.time), transform.position.y, transform.position.z);
     
 
         //For Jumping 
         if (buttonPressed && isGrounded && LevelSettings.gameStarted)
         {
             //animator.SetBool("jump", true);
             float y = transform.position.y;
             y += jumpPower * Time.deltaTime * gravity;
             isGrounded = false;
             rb.AddForce(new Vector2(0, jumpPower));
         }
         buttonPressed = false;
     //update camera position
         if (!(main.transform.position.x >= transform.position.x))
         {
             Vector3 cameraPos = main.transform.position;
              cameraPos.x = transform.position.x;
             //cameraPos.y = player.position.y;
             main.transform.position = cameraPos;
         }
     }
     int interval = 3;
     void Update(){
         if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0))
         {
             buttonPressed = true;
         }
         if (Time.frameCount % interval == 0)
         {
 
             checkForGameOver();/// <summary>
             //this function must be on undate not on fixed update
         }
          
                 
         
     }
 
    
     bool isCollided = false;
     void OnCollisionEnter2D(Collision2D collision)
     {
         //For Jumping 
         animator.SetBool("jump", false);
       if(rabbit_controller.rb.velocity.y<=1)
         isGrounded = true;
         //If Player Wins 
         if (collision.collider.tag == "win")
         {
 
             win = true;
             GameObject.Find("home").GetComponent<Animator>().SetBool("close", true);
             GameObject.Find("home").GetComponent<Animator>().SetBool("open", false);
             if (!winAud.isPlaying)
                 winAud.Play();
         }
         
         if (collision.collider.tag == "pot") {
             score_controller.score--;
             score_controller.scoreChanged = true;
         }
 
     }
 
     void OnCollisionExit(Collision collisionInfo)
     {
         
             isCollided = true;
         
     }
     void OnTriggerEnter2D(Collider2D collider)
     {
         if (collider.tag == "win")
         {
 
             GameObject.Find("home").GetComponent<Animator>().SetBool("open", true);
         }
        
     }
     public static IEnumerator  kill()
     {
        
 
           
             if (!isDead)
             {
                 
                 animator.SetBool("dead", true);
                 if (!scrmAud.isPlaying)
                     scrmAud.Play();
 
                 score_controller.tries++;
 
                 GameObject gameOver = Instantiate(Resources.Load<GameObject>("Sprite/menu/gameOver"));
 
                 gameOver.transform.position = new Vector3(Camera.main.transform.position.x, gameOver.transform.position.y, -0.3f);
                 if (score_controller.tries % 9 == 0)
                 {
                     //Show Ads
                     MonoBehaviour.print("Showing Ads");
                     googleAdMob.RequestInterstitial();
                 }
                 score_controller.tries++;
                 if (!failAud.isPlaying)
                     failAud.Play();
                 isDead = true;
             }
            
            
             //rb.AddForce (new Vector2 (0, 200f));
             //    yield return new WaitForSeconds(0.2f);
 
             yield return new WaitForSeconds(0.3f);
             Time.timeScale = 0;
             LevelSettings.gameStarted = false;
 
        
     }
     
     private void checkForGameOver(){
         //The player is basically game over
         if (transform.position.y < -1&&!godMode&&!isDead) {
             StartCoroutine(kill());
         }
 
     }
     
     public static void restart() {
 
         score_controller.scoreChanged = false;
         food_spawner.totalScore = 0;
         score_controller.score = 0;
         isDead = false;
         win = false;
         LevelSettings.gameStarted = false;
         int scene = SceneManager.GetActiveScene().buildIndex;
         LevelSettings.gameStarted = true;
         Time.timeScale = 1;
         SceneManager.LoadScene(scene, LoadSceneMode.Single);
 
     }
 
    
      
 
 }

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 mgear · Apr 03, 2018 at 05:52 AM 1
Share

check with Profiler to see which part of the game is causing it (can profile in editor first to see if anything obvious, if not, then Profile in connected device)

avatar image meat5000 ♦ · Apr 03, 2018 at 10:56 AM 0
Share

If LevelSettings is not a static object then the way you are trying to access it will throws errors that will lag Android. Use LogCat to see this.

3 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by tormentoarmagedoom · Apr 03, 2018 at 07:32 AM

Good day.

As losingisfun said, you should replace the GameObject.Find.

Add a new tag named "home" and assign it to Home. And then Use GameObject.FindObjectWithTag = "Home".

What you mean by lag. Time to load the scene? scene goes slowly? There is audio in the scene? Cometimes audio is heavy and needs to be decompressed or loaded before/during scene... you should check this if you have music/sounds

The rest os the script don't semms to bee "hard to process"... so.. are you sure is this script?

Bye :D

Comment
Add comment · Show 3 · 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
avatar image noorkaximi · Apr 03, 2018 at 10:19 AM 0
Share

the game runs fine when i disable this script so i think this is the main reason

avatar image noorkaximi · Apr 03, 2018 at 10:21 AM 0
Share

audio is not the problem its only play when an event occurs..

avatar image kskjadav007 · Jan 22, 2020 at 07:00 AM 0
Share

Don't use GameObject.Find method use something else insted of this and see perfomance .

avatar image
1

Answer by losingisfun · Apr 03, 2018 at 05:46 AM

well you are using GameObject.Find which is a costly method. I would find another way to do this, or store the data especially for the line GameObject.Find("home")

Comment
Add comment · Show 2 · 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
avatar image noorkaximi · Apr 03, 2018 at 07:15 AM 1
Share

this condition will run only once when the player wins. but the game lag from the beginning . so i don't this is the problem

avatar image noorkaximi · Apr 03, 2018 at 07:23 AM 0
Share

it lags when the jump condition gets triggered

avatar image
1

Answer by Harinezumi · Apr 03, 2018 at 07:49 AM

I think the problem is that you are moving your game object with physics as well as with transform.position (in FixedUpdate(), you assign the position in every physics frame). I can't find the forum thread about the performance comparison, but basically if you have a Rigidbody on your game object, then assigning transform.position is the worst thing you can do. If you then also apply a force, the physics engine freaks out, hence the lag when jump condition is triggered (although this is a bit of a guess).

Instead, using Rigidbody.position is the recommended way, or even better, Rigidbody.MovePosition() for continuous movement. Try this, and see if the performance improves. If not, then do a deep profile and check which exact part is causing the issue (if it is physics, the complexity of the script, or something else).

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

86 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

Related Questions

Dynamic shadows decrease performance in android. 1 Answer

Minimum API Level and Performance in Android Build 0 Answers

Just One of my scene is so laggy 0 Answers

Game lagging so much on android 0 Answers

Shader.Parse processing shaders that are not included in build 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