Lives resetting on death

Hello!

Finding an issue were when my player dies the lives reset.
It goes from 3 lives and flickers to 2 only to go back to 3.

I’ve narrowed down the issue to be within my TileGameSession script
and apart of the line;

SceneManager.LoadScene(currentSceneIndex);

within my TileGameSession script.

I have put the level within the scene build so after that I’m not sure where I’m going wrong.
Any help in the right direction would be appreciated.


edit: Point accumulation is also not saving. It’s looking more like a full unity/script error and I’m going to rewrite it all.


PlayerMovement Script


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerMovement : MonoBehaviour {

[SerializeField] float runSpeed = 5f;
[SerializeField] float jumpSpeed = 5f;
[SerializeField] Vector2 deathKick = new Vector2(10, 0);
[SerializeField] float climbSpeed = 5f;

private int jumpCount = 0;
private int maxJumps = 2;

private Animator myAnimator;
// States
bool isAlive = true;

// Cached component references
public Rigidbody2D myRigidBody;
CapsuleCollider2D myBodyCollider2D;
PolygonCollider2D myFeet;
float gravityScaleAtStart;


void Start () {
    myAnimator = gameObject.GetComponent<Animator>();
    myRigidBody = gameObject.GetComponent<Rigidbody2D>();
    myBodyCollider2D = gameObject.GetComponent<CapsuleCollider2D>();
    myFeet = gameObject.GetComponent<PolygonCollider2D>();
    gravityScaleAtStart = myRigidBody.gravityScale;
}

void Update()
{
    // if the player is not alive then turn off the ability to Run,Jump,etc.
    if (!isAlive) { return; }

    FlipSprite();
    Die();
    Run();
    ClimbLadder();
    Jump();
}

// Flip sprite dependant on direction
private void FlipSprite()
{
    bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;
    if (playerHasHorizontalSpeed)
    {
        transform.localScale = new Vector2(Mathf.Sign(myRigidBody.velocity.x), 1f);
    }
}

private void Die()
{
    if (myBodyCollider2D.IsTouchingLayers(LayerMask.GetMask("Enemy", "Hazards")))
    {
        isAlive = false;
        myAnimator.SetTrigger("Dying");
        GetComponent<Rigidbody2D>().velocity = deathKick;     
        FindObjectOfType<TileGameSession>().ProcessPlayerDeath();
    }
}

// Run
private void Run()
{        
    float controlThrow = CrossPlatformInputManager.GetAxis("Horizontal");
    Vector2 playerVelocity = new Vector2(controlThrow * runSpeed, myRigidBody.velocity.y);
    myRigidBody.velocity = playerVelocity;    
    
    bool playerHasHorizontalSpeed = Mathf.Abs(myRigidBody.velocity.x) > Mathf.Epsilon;
    myAnimator.SetBool("Running", playerHasHorizontalSpeed);
}

// Climb
private void ClimbLadder()
{
    if(!myBodyCollider2D.IsTouchingLayers(LayerMask.GetMask("Climbing")))
    {
        myAnimator.SetBool("Climbing", false);
        myRigidBody.gravityScale = gravityScaleAtStart;
        return;
    }

    float controlThrow = CrossPlatformInputManager.GetAxis("Vertical");
    Vector2 climbVelocity = new Vector2(myRigidBody.velocity.x, controlThrow * climbSpeed);
    myRigidBody.velocity = climbVelocity;
    myRigidBody.gravityScale = 0f;

    bool playerHasVerticalSpeed = Mathf.Abs(myRigidBody.velocity.y) > Mathf.Epsilon;
    myAnimator.SetBool("Climbing", playerHasVerticalSpeed);
}

// Jump
private void Jump() {

    if (!myFeet.IsTouchingLayers(LayerMask.GetMask("Grounded"))) { return; }
    print("Feet on the ground");
    if (CrossPlatformInputManager.GetButtonDown("Jump"))
    {
        Vector2 jumpVelocityToAdd = new Vector2(0f, jumpSpeed);
        myRigidBody.velocity += jumpVelocityToAdd;
        print("jumping");
    }       
}

}

TileGameSession Script


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class TileGameSession : MonoBehaviour {

[SerializeField] int playerLives = 3;
[SerializeField] int score = 0;

[SerializeField] Text livesText;
[SerializeField] Text scoreText;

void Awake()
{
    int numGameSessions = FindObjectsOfType<TileGameSession>().Length;
    if (numGameSessions > 1)
    {
        Destroy(gameObject);
    }
    else
    {
        { return; }
    }
}

// Use this for initialization
void Start () {
    livesText.text = playerLives.ToString();
    scoreText.text = score.ToString();
}

public void AddToScore (int pointsToAdd)
{
    score += pointsToAdd;
    scoreText.text = score.ToString();
}

public void ProcessPlayerDeath()
{
    if (playerLives > 1)
    {
        TakeLives();
    }
    else
    {
        ResetGameSession();
    }
}

private void TakeLives()
{
    playerLives--;
    //Reset level on death
    var currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
    //// resetting without maintining life decrease
    // SceneManager.LoadScene(currentSceneIndex);
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    livesText.text = playerLives.ToString();
}

private void ResetGameSession()
 {
    Destroy(gameObject);
    SceneManager.LoadScene(0);
 }
}

Not to this section of the course yet, but I’ll take a stab at it. playerLives has it’s value set to, in this case, 3, when the scene is loaded. If you simply reload the scene to reset everything, playerLives is among the variables that will be reset to their default values.

Try: (in the TakeLives method)
int tempLives;
playerLives–;
tempLives = playerLives;
SceneManager.LoadScene(SceneManager.GetActiveScene().BuildIndex);
playerLives = tempLives;
livesText.text = playerLives.ToString();

EDIT: Think I’m done with the 1000 edits I needed to get my scatter-brained thoughts organized into text.

1 Like

I really appreciate you replying to this post.

The method you purposed has the lives reducing to 0 and once again flickering back to 3.
Both of these methods should work though… As I keep reading them over and over I’m baffled at what the issue may be. I’m going to delete/rewrite all the components that involve this game function. Hopefully It comes back as a Unity error, which I’ve come across, and not a script error…

I loathe starting from scratch, but I can appreciate when you run into a frustrating wall. You may try using the static keyword (the variable would be associated with the class, not an instance of the class) on your lives variable before you try a full recode. I really don’t know how Unity plays with serialized static variables, but it’s worth a try.

1 Like

Colton… Colton, Colton, Colton…

static int playerLives = 3;

over

[SerializeField] int playerLives = 3;

worked…

Colton, Colton, Colton… I had my hands on my face thinking of rewritting it all and coming to the realization that thats exactly what I needed to do… Thank you.

Good deal! Be something I’ll have to file away for later.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms