- Home /
Game is not restarting after gameOver=true
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement;
public class Player : MonoBehaviour {
private Rigidbody2D playerRb;
public Text ScoreDisplay;
public float scoreDisplayText=0;
public float jumpSpeed=5.0f;
public float movingSpeed=2.0f;
public float verticalLimit=4.35f;
public float gravityScale;
private bool isMoving;
private bool gameOver;
public Text gameOverText;
// Start is called before the first frame update
void Start()
{
playerRb=gameObject.GetComponent<Rigidbody2D>();
playerRb.gravityScale=0;
ScoreDisplay.gameObject.SetActive(false);
gameOverText.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
if(transform.position.y>verticalLimit){
transform.position=new Vector3(transform.position.x,verticalLimit,transform.position.z);
playerRb.velocity=new Vector2(playerRb.velocity.x,0);
}
else if(transform.position.y<-verticalLimit){
transform.position=new Vector3(transform.position.x,-verticalLimit,transform.position.z);
playerRb.velocity=new Vector2(playerRb.velocity.x,0);
}
if(Input.GetAxis("Fire1")==1f){//if something is being pressed the result from axis is going to be 1
playerRb.velocity=new Vector2(playerRb.GetComponent<Rigidbody2D>().velocity.x,jumpSpeed);
playerRb.gravityScale=gravityScale;
ScoreDisplay.gameObject.SetActive(true);
if(isMoving==false){
isMoving=true;
startMoving();
}
}
if(gameOver==true && (Input.GetAxis("Fire1")==1f)){
SceneManager.LoadScene("Game");
}
}
void startMoving(){
playerRb.velocity=new Vector2(movingSpeed,jumpSpeed);
}
void OnTriggerEnter2D(Collider2D otherCollider){
if(otherCollider.gameObject.tag=="Obstacle"){
Destroy(gameObject);
ScoreDisplay.gameObject.SetActive(false);
gameOver=true;
}
else if(otherCollider.gameObject.tag=="ScoreTrigger"){
Destroy(otherCollider.gameObject);
scoreDisplayText+=1;
ScoreDisplay.text="Score: " + scoreDisplayText;
}
}
}
Answer by yummy81 · May 02, 2020 at 07:09 AM
Look at this piece of your code:
void OnTriggerEnter2D(Collider2D otherCollider){
if(otherCollider.gameObject.tag=="Obstacle"){
Destroy(gameObject);
ScoreDisplay.gameObject.SetActive(false);
gameOver=true;
}
When you collide with Obstacle, at first you destroy gameObject, and later you want to make the gameOver boolean be set to true. But you can't do that, because you destroyed the gameObject, so all your code simply do not work anymore. Try to remove this line:
Destroy(gameObject);
Then, are you sure that this piece of code will have a chance to be executed?
if(gameOver==true && (Input.GetAxis("Fire1")==1f)){
Scene$$anonymous$$anager.LoadScene("Game");
}
If you load new scene, your object will be destroyed anyway
correct...after all what is the point of destroying an object that is about to be destroyed due to scene change. In that case I believe it is better to put at the beginning of the Update
if(gameOver==true) return;