- Home /
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);
}
}
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)
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.
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
the game runs fine when i disable this script so i think this is the main reason
audio is not the problem its only play when an event occurs..
Don't use GameObject.Find method use something else insted of this and see perfomance .
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")
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
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).