How to Fix Issue with GameManager and OnCollisionEnter2D functions?

Hello! I’m a bit new to Unity, so I’ve been doing my best to solve problems without going to the forums for every little issue. There is one bug that I just cannot figure out how to get past.

While trying to create a heart management system, the majority of code already reaches proper breakpoint conditions (in the debugger) and does as it should, which means my heart management system in about 70% of the way there. However, the same OnCollisionEnter2D script that works in sections like LivesManager and PlayerMovement, does not work in the GameManager, which means my array for managing hearts does not work. Since my array is in Update and GameManager, having the OnCollisionEnter2D working there is essential. Would anyone have a good fix for this problem that matches the syntax I have going? Everything is rather simple for the code that supports this function, which I’ll document briefly below in two parts:

Part 1:
For PlayerMovement, the function that exists for OnCollisionEnter2D is a valid breakpoint when lives are lost so when I run into a trap, the debugger is happy:

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;
    private BoxCollider2D coll;
    private SpriteRenderer sprite;
    private Animator anim;

    private GameManager _theGM;
    public LivesManager _theLM;

    public int defaultLives;
    public int livesCounter;

    [SerializeField] private LayerMask jumpableGround;

    private float dirX = 0f;
    [SerializeField] private float moveSpeed = 7f;
    [SerializeField] private float jumpForce = 14f;

    private enum MovementState { idle, running, jumping, falling }
 
    [SerializeField] private AudioSource jumpSoundEffect;

    private void Start()
    {
        _theLM = FindObjectOfType<LivesManager>();
        livesCounter = defaultLives;
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<BoxCollider2D>();
        sprite = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();
    }

    private void Update()
    {
        dirX = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            jumpSoundEffect.Play();
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }
  
     UpdateAnimationState();
  
    }
 


    private void UpdateAnimationState()
    {
        MovementState state;

             if (dirX > 0f)
        {
            state = MovementState.running;
            sprite.flipX = false;
        }
        else if (dirX < 0f)
        {
            state = MovementState.running;
            sprite.flipX = true;
        }
        else
        {
            state = MovementState.idle;
        }


        if (rb.velocity.y > .1f)
        {
            state = MovementState.jumping;
        }
        else if (rb.velocity.y < -.1f)
        {
            state = MovementState.falling;
        }

        anim.SetInteger("state", (int)state);
    }

    private bool IsGrounded()
        {
            return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
        }

        private void OnCollisionEnter2D(Collision2D collision)
        {
            if(collision.gameObject.tag == "Trap")
            {
                GameManager.health -=1;
                _theLM.TakeLife();
            }
     
        }
}

Part 2:
My LivesManager should be setup correctly (everything debugs as it should), which already takes into account whenever the player runs into “Trap” tagged objects; so Collision is functioning perfectly. You can see my syntax approach best, here:

public class LivesManager : MonoBehaviour
{
    public int defaultLives;
    public int livesCounter;
    public GameObject heart0, heart1, heart2, heart3;

    public Text livesText;

    [SerializeField] private GameManager _theGM;
    [SerializeField] LivesManager _theLM;

    [SerializeField] private Text LivesCounterText;
    [SerializeField] private GameObject LivesSprite;

    void Start()
    {
      livesCounter = defaultLives;

      _theGM = FindObjectOfType<GameManager>();
    }

    void Update()
    {
        livesText.text = "Hearts " + livesCounter;

        if(livesCounter <1)
        {
            _theGM.GameOver();
        }
    }

    public void TakeLife()
    {
        livesCounter--;
    }


}

The GameManager Problem
Here’s where the problem is, and it is only part of the script that is the culprit. After testing all my code to make sure it is working as it should, it all leads back to an issue in GameManager. Because the OnCollisionEnter2D is not initializing, the array cannot be updated properly. This makes the hearts reset from 3, back to 4 after the game resets.

public class GameManager : MonoBehaviour
{
    public List<GameObject> HeartUiObjects = new();
    public int defaultLives;
    public int livesCounter;
    public PlayerMovement thePlayer;
    private Vector2 playerStart;

    public GameObject gameOverScreen;
    public GameObject victoryScreen;

    public static int health;
    private GameManager _theGM;
    public LivesManager _theLM;

    void Start()
    {
        _theLM = FindObjectOfType<LivesManager>();
        livesCounter = defaultLives;
        defaultLives = health;
        playerStart = thePlayer.transform.position;
        health = 4;
        gameOverScreen.gameObject.SetActive(false);
  
    }

    void Update()
    {
  
        // In this loop, we expect HeartUiObjects to have a count of 4.
        // Thus, i will start at 0 and iterate { 0, 1, 2, 3 }
        for(int i = 0; i < HeartUiObjects.Count; i++)
        {
            // if we don't add 1 to i we will see an off-by-one error
            if(health < i + 1)
            {
          
                HeartUiObjects[i].SetActive(false);
                victoryScreen.gameObject.SetActive(false);
          
          
            }
            else
            {
                HeartUiObjects[i].SetActive(true);
                victoryScreen.gameObject.SetActive(false);
            }
        }

        if(health <= 0)
        {
            gameOverScreen.gameObject.SetActive(true);
            victoryScreen.gameObject.SetActive(false);
            Time.timeScale = 0;
        }
  

    }

        private void OnCollisionEnter2D(Collision2D collision)
        {
            if(collision.gameObject.tag == "Trap")
            {
                GameManager.health -=1;
                _theLM.TakeLife();
            }
  
        }

    public void Victory()
    {
        victoryScreen.SetActive(true);
        thePlayer.gameObject.SetActive(false);
        gameOverScreen.SetActive(false);
    }

    public void GameOver()
    {
        victoryScreen.SetActive(false);
        gameOverScreen.SetActive(true);
        thePlayer.gameObject.SetActive(false);
    }

    public void Reset()
    {
        victoryScreen.SetActive(false);
        gameOverScreen.SetActive(false);
        thePlayer.gameObject.SetActive(true);
        thePlayer.transform.position = playerStart;
    }
}

The issue may be that Collision needs to reference “The Player” and “Trap” tag so that they can collide and it registers, but I don’t know how I’d go about doing that? Everything else but this area (OnCollision2D for GameManager) runs smoothly, so I’d like to avoid rewriting a lot of this code if possible. I am rather new, so I’m still learning exactly how to setup objects to interact with each other correctly.

Any help would be appreciated!

I assume GameManager is not a component of the same object as PlayerMovement belongs to, when that object collides only PlayerMovement.OnCollisionEnter2D will be called. You could just call _theGM.OnCollisionEnter2D (although it should be public and provably have a different name) from PlayerMovement.OnCollisionEnter2D. I see you’re not initializing PlayerMovement._theGM though, so you should do it like in LivesManager.Start. Or just configure it from the editor (previously tagging it with [SerializeField] like in LivesManager so it’s listed in the inspector).

How would you go about naming the OnCollisionEnter2D so that it has a different naming convention compared to the traditional ‘private void OnCollision2D’ naming structure? Could you provide an example of how that code would look? Naming conventions are something I’m still getting used to, but seeing it correct will help with me applying it in future situations. That right there would ensure organization and making sure I don’t modify the overall OnCollision2D when it gets called more and more across objects (since the goal is to have these values public)

I have set up the GameManager (in PlayerMovement) to be a SerializeField and assigned it to the GameManager, (and I’ll be getting some sleep too because that will help with project perspective too) so that should also ensure everything works on top of the other recommendations.

Naming conventions are always a sticky subject since everyone has their own definition of intuitive. Given the function body I’d move the trap tag comparison to the caller and just rename it to TakeDamage (and pass the amount of health to subtract by parameter). So for PlayerMovement:

private void OnCollisionEnter2D(Collision2D collision)
{
    if(collision.CompareTag("Trap")
   {
        _theGM.TakeDamage(1);
   }
}

And for GameManager:

public void TakeDamage(int healthTaken)
{
    health -=healthTaken;
    _theLM.TakeLife();
}

Although I can see your current PlayerMovement.OnCollisionEnter2D is already identical to GameManager.OnCollisionEnter2D, so even if the later is not called you should already be getting the desired functionality. Is this a temporal workaround? Is GameManager.Update getting called?
Also, I’d refrain from exposing GameManager.health as a public static member.

EDIT: Hmmm… on closer inspection I’m not really sure this is a good approach at all. Most likely you want PlayerManager to call _theLM.TakeLife and, inside that method notify GameManager what’s the new health. Also, I’m not sure if I misunderstood, but aren’t GameManager.health and LivesManager.livesCounter the same thing?

Based on the initial tutorial I watched (which can be where a lot of bad code is written) it was done so that if values update in one, you can have it reflected in the other script. That may not be most optimal, which I’ll optimize better once I nail fixing this bug. Good thing with the GameManager, it does a valid breakpoint now, which will help with what my plans are with the array.

My approach to separating the array and theTakeDamage function is for the sake of me separating the array and OnCollision2D since the collision wouldn’t debug, meaning that if I were to throw it into the invalid breakpoint function, nothing would happen. The array and OnCollision will be merged soon, and that should help with the array updating since it’ll be in a statement that is called only when necessary (instead of me having to fiddle with Update and a function I only want to call once). I take this would manage the array at least so the values update?

The problem now with my approach is that there are several terms not defined. For example, our newly created TakeDamage function lacks any definition, so when it gets referenced, it has nothing to modify the array, hence the lack of hearts decreasing but then increasing again. That means it is getting called, it just lacks a definition. In the Game Manager (and potentially for the other areas, in case it is different), could you possibly give an example on how to set that up? Once I understand how to get a definition to these objects, the issue should hopefully be resolved!

I’m deeply sorry @ryanwiseman but I don’t understand what you mean by not defined. I’m more used to C++ than C#, but I don’t think it’s possible to declare a method in C# without defining it (that is, writing the method body). If you try to call an undefined method it should simply not compile at all.

I completely agree with you setting-up your hearts visibility in an Update is not the best idea. In fact, I think you could simply change in your GameManager void Update() to something like public void OnLivesChanged(int health) and call it from LivesManager.TakeLife. That way you can get rid of GameManager.health and remove the risk of introducing data redundancy errors.
So in the end things would look like this:

  • PlayerMovement:
private void OnCollisionEnter2D(Collision2D collision)
{
    if(collision.CompareTag("Trap")
   {
        _theLM.TakeLife();
   }
}
  • LifeManager:
public void TakeLife()
{
    livesCounter--;
    livesText.text = "Hearts " + livesCounter;
    _theGM.OnLifeChanged(livesCounter);
}
  • GameManager:
public void OnLifeChanged(int health)
{
    //Basically the same code currently in Update
}

Now you can also get rid of LivesManager.Update, as GameManager.OnLivesChanged already checks the game over condition.

On the other hand, regarding this sentence in your first post: “This makes the hearts reset from 3, back to 4 after the game resets.” What do you mean by “after the game resets”? Do you mean after stopping and restarting the game? If that’s the case, it’s completely normal it gets reset, as there is no data that survives between sessions. If that’s what you want you’ll need to use some kind of persistence mechanism. I’m sorry I can’t help you much in that regard as I don’t yet know what functionality does Unity provide for that.

Good news, the bug is 90% resolved, I finally was able to get things to reference as they should, it’s just this small little area. I was trying to understand how to assign a definition to a function, since a few of mine had none. Idk if you use VS/VSCode, but you can right click and select Go To Definition on any function or term that is available. It’s one of the greatest tools I’ve just started taking advantage of. For any function that lacks a definition, means that if you apply the function to another function, nothing will happen.

So the problem was that functions like TakeDamage, when you pulled the definition, lacked one (usually you want it paired to something like GameManager). In VSCode, you can right click and have an option of “Go To Definition”. I was able to get TakeDamage to finally be defined, which now, if I run into hearts, I get the hearts to go down to 3, but a Game Over screen happens. Without TakeDamage defined, nothing in the array would update.

The GameManager.OnLivesChanged was not needed. However, if I do not have LiveManager.Update, it doesn’t manage my hearts at all, so we still would want that.

The current problem is that when I run into spikes, my health drops to 3 permanently (which is good) and gives me a Game Over screen. This is because GameOver isn’t defined in the LivesManager. Any idea of what would be best to do so?

I’ll play around with this code more today, but so far, I’ve narrowed down the bug to this area alone. Once I get this finally resolved, I will post the very specific code needed, in case someone stumbles upon this thread with the same problem.

Here’s what my current setup looks like:
PlayerMovement

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;
    private BoxCollider2D coll;
    private SpriteRenderer sprite;
    private Animator anim;

    [SerializeField] GameManager _theGM;
    public LivesManager _theLM;

    public int defaultLives;
    public int livesCounter;
    public int TakeLife;
    public int TakeDamage;

    [SerializeField] private LayerMask jumpableGround;

    private float dirX = 0f;
    [SerializeField] private float moveSpeed = 7f;
    [SerializeField] private float jumpForce = 14f;

    private enum MovementState { idle, running, jumping, falling }
 
    [SerializeField] private AudioSource jumpSoundEffect;

    private void Start()
    {
        _theLM = FindObjectOfType<LivesManager>();
        _theGM = FindObjectOfType<GameManager>();
        livesCounter = defaultLives;
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<BoxCollider2D>();
        sprite = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();
    }

    private void Update()
    {
        dirX = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            jumpSoundEffect.Play();
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }
 
     UpdateAnimationState();

 
    }
 


    private void UpdateAnimationState()
    {
        MovementState state;

             if (dirX > 0f)
        {
            state = MovementState.running;
            sprite.flipX = false;
        }
        else if (dirX < 0f)
        {
            state = MovementState.running;
            sprite.flipX = true;
        }
        else
        {
            state = MovementState.idle;
        }


        if (rb.velocity.y > .1f)
        {
            state = MovementState.jumping;
        }
        else if (rb.velocity.y < -.1f)
        {
            state = MovementState.falling;
        }

        anim.SetInteger("state", (int)state);
    }
    private bool IsGrounded()
        {
            return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
        }

        private void OnCollisionEnter2D(Collision2D collision)
        {
            if(collision.gameObject.tag == "Trap")
            {
                _theGM.TakeDamage(1);
                _theLM.TakeLife();
            }
    
        }
}

LivesManager

public class LivesManager : MonoBehaviour
{
    public int defaultLives;
    public int livesCounter;
    public GameObject heart0, heart1, heart2, heart3;
    public GameObject gameOverScreen;
    public Text livesText;

    [SerializeField] private GameManager _theGM;
    [SerializeField] LivesManager _theLM;
    [SerializeField] private Text LivesCounterText;
    [SerializeField] private GameObject LivesSprite;

 
    void Start()
    {
      livesCounter = defaultLives;
      _theGM = FindObjectOfType<GameManager>();
    }


    void Update()
    {
        livesText.text = "Hearts " + livesCounter;

        if(livesCounter <1)
        {
            _theGM.GameOver();
        }
    }

    public void TakeLife()
    {
        livesCounter--;

    }


}

GameManager

public class GameManager : MonoBehaviour
{
    public List<GameObject> HeartUiObjects = new();
    public int defaultLives;
    public int livesCounter;
    public PlayerMovement thePlayer;
    private Vector2 playerStart;

    public GameObject gameOverScreen;
    public GameObject victoryScreen;

    public static int health;
    private GameManager _theGM;
    public LivesManager _theLM;

    void Start()
    {
        _theLM = FindObjectOfType<LivesManager>();
        livesCounter = _theLM.livesCounter;
        livesCounter = defaultLives;
        defaultLives = health;
        playerStart = thePlayer.transform.position;
        gameOverScreen.gameObject.SetActive(false);
        victoryScreen.gameObject.SetActive(false);
    }

 
    public void TakeDamage(int healthTaken)
    {
        health -=healthTaken;
    
        for(int i = 0; i < HeartUiObjects.Count; i++)
        {
            {
                HeartUiObjects[i].SetActive(false);
                gameOverScreen.gameObject.SetActive(false);
                victoryScreen.gameObject.SetActive(false);
            }
            else
            {
                HeartUiObjects[i].SetActive(false);
                gameOverScreen.gameObject.SetActive(false);
                victoryScreen.gameObject.SetActive(false);
            }
        }

        if(health <= 0)
        {
            gameOverScreen.gameObject.SetActive(true);
            victoryScreen.gameObject.SetActive(false);
            Time.timeScale = 0;
        }
    }

 

    public void Victory()
    {
        victoryScreen.SetActive(true);
        thePlayer.gameObject.SetActive(false);
        gameOverScreen.SetActive(false);
    }

    public void GameOver()
    {
        victoryScreen.SetActive(false);
        gameOverScreen.SetActive(true);
        thePlayer.gameObject.SetActive(false);
    }

    public void Reset()
    {
        victoryScreen.SetActive(false);
        gameOverScreen.SetActive(false);
        thePlayer.gameObject.SetActive(true);
        thePlayer.transform.position = playerStart;
    }
}

EDIT: There are actually a few areas that do not return to a valid breakpoint. Idk if you would be able to check the code to make sure I’m not running into anymore additional issues, but yeah, there are still some additional problems that will be bugging me (pun unintentional) until I finally resolve them

The reason why it’s giving you a game over screen after taking one hit it’s because GameManager.health is never initialized and so it’s already 0 from the beginning. Thus, when PlayerMovement.OnCollisionEnter2D calls _theGM.TakeDamage(1), GameManager.health becomes -1. Later down that method it checks if(health <= 0) and it passes, thus activating this the game over screen. This is the reason why I consider a bad idea having the lives counter repeated in LivesManager and GameManager.

Yes, I use Visual Studio, but I’m not sure how it’s possible your code compiled if TakeDamage was not defined. Unity should have given you an error message similar to this one (please disregard the PlayerController name):


And then something like this when you tried to run it:

As for method GameOver not being defined in LivesManager, I don’t see the need. You’re calling _theGM.GameOver(), and _theGM is a GameManager object.

Idk why we would have different issues with definitions, maybe there’s an issue with the inspector on your end? I also did some further defining by using the Inspector when I click on the script itself. That may help with the problem you are running into?

The TakeDamage should be referencing the array, it does on my end. I’ll post the three sections of code, hopefully you don’t run into an issue with TakeDamage being not defined.

After a bit of fiddling, I was able to get the default number of lives to 4 and decrease to 3 without the GameOver screen. In doing so, I managed to skip my death animation, while also forcing my player into a permanent static state. I don’t know what is causing it, but the problem is almost fixed. Any idea of what I should do to get it to work?

There will be a bit of code cleanup I do after getting this problem resolved, since there are better ways of writing it

Player Manager

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;
    private BoxCollider2D coll;
    private SpriteRenderer sprite;
    private Animator anim;

    [SerializeField] GameManager _theGM;
    public LivesManager _theLM;
    [SerializeField] PlayerMovement _thePM;

    public PlayerMovement thePlayer;
    private Vector2 playerStart;

    public int defaultLives;
    public int livesCounter;
    public int TakeLife;
    public int TakeDamage;

    [SerializeField] private LayerMask jumpableGround;

    private float dirX = 0f;
    [SerializeField] private float moveSpeed = 7f;
    [SerializeField] private float jumpForce = 14f;

    private enum MovementState { idle, running, jumping, falling }
   
    [SerializeField] private AudioSource jumpSoundEffect;

    // Start is called before the first frame update
    private void Start()
    {
        _theLM = FindObjectOfType<LivesManager>();
        _theGM = FindObjectOfType<GameManager>();
        _thePM = FindObjectOfType<PlayerMovement>();
        livesCounter = defaultLives;
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<BoxCollider2D>();
        sprite = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();
        playerStart = transform.position;
    }

    void Awake()
    {
        playerStart = transform.position;
    }
    // Update is called once per frame
    public void Update()
    {
        dirX = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            jumpSoundEffect.Play();
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }
    
     UpdateAnimationState();
    
    }

    private void UpdateAnimationState()
    {
        MovementState state;

             if (dirX > 0f)
        {
            state = MovementState.running;
            sprite.flipX = false;
        }
        else if (dirX < 0f)
        {
            state = MovementState.running;
            sprite.flipX = true;
        }
        else
        {
            state = MovementState.idle;
        }


        if (rb.velocity.y > .1f)
        {
            state = MovementState.jumping;
        }
        else if (rb.velocity.y < -.1f)
        {
            state = MovementState.falling;
        }

        anim.SetInteger("state", (int)state);
    }
    private bool IsGrounded()
        {
            return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
        }

        private void OnCollisionEnter2D(Collision2D collision)
        {
            if(collision.gameObject.tag == "Trap")
            {
                _theGM.TakeDamage(1);
                _theLM.TakeLife();
        }
     }

}

GameManager

public class GameManager : MonoBehaviour
{
    public List<GameObject> HeartUiObjects = new();
    //Public Int values can be helpful to the components that need defin
   
    public int defaultLives;
    public int livesCounter;
    public int victoryScreen;
    public int gameOverScreen;
    public PlayerMovement thePlayer;
    private Vector2 playerStart;

    public static int health;
    private GameManager _theGM;
    public LivesManager _theLM;
    public PlayerMovement _thePM;

    private Rigidbody2D rb;
    private BoxCollider2D coll;
    private Animator anim;

    void Start()
    {
        _theLM = FindObjectOfType<LivesManager>();
        _theGM = FindObjectOfType<GameManager>();
        _thePM = FindObjectOfType<PlayerMovement>();
        livesCounter = _theLM.livesCounter;
        defaultLives = health;
        defaultLives = 4;
        playerStart = thePlayer.transform.position;
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<BoxCollider2D>();
        anim = GetComponent<Animator>();
       
    }

    void Awake()
    {
        playerStart = transform.position;
    }
   
    public void TakeDamage(int healthTaken)
    {
        health -=healthTaken;
         // In this loop, we expect HeartUiObjects to have a count of 4.
        // Thus, i will start at 0 and iterate { 0, 1, 2, 3 }
       
        for(int i = 0; i < HeartUiObjects.Count; i++)
       
        {
            // if we don't add 1 to i we will see an off-by-one error
            if(health < i + 1)
            {
                HeartUiObjects[i].SetActive(false);
            }
            else
            {
                HeartUiObjects[i].SetActive(false);
            }
            if (health <i - 1)
            {
                thePlayer.gameObject.SetActive(true);
                thePlayer.transform.position = playerStart;
            }
        }

        if(health <= 0)
        {
            Time.timeScale = 0;
            rb.bodyType = RigidbodyType2D.Static;
        }
    }

    

    public void Victory()
    {
        thePlayer.gameObject.SetActive(false);
    }

    public void GameOver()
    {
        thePlayer.gameObject.SetActive(false);
    }

    public void Reset()
    {
        thePlayer.gameObject.SetActive(true);
        thePlayer.transform.position = playerStart;
    }

}

LivesManager

public class LivesManager : MonoBehaviour
{
    public int defaultLives;
    public int livesCounter;
    public int health;
    public GameObject heart0, heart1, heart2, heart3;
    public GameObject gameOverScreen;
    public GameObject victoryScreen;
    public PlayerMovement thePlayer;

    private Rigidbody2D rb;
    private Animator anim;

    public Text livesText;

    [SerializeField] GameManager _theGM;
    [SerializeField] LivesManager _theLM;
    [SerializeField] PlayerMovement _thePM;


    [SerializeField] private Text LivesCounterText;
    [SerializeField] private GameObject LivesSprite;

   

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        health = 4;
        defaultLives = 4;
        livesCounter = _theLM.livesCounter;
        defaultLives = health;
        _theGM = FindObjectOfType<GameManager>();
        _theLM = FindObjectOfType<LivesManager>();
        _thePM = FindObjectOfType<PlayerMovement>();
        victoryScreen.gameObject.SetActive(false);
        gameOverScreen.SetActive(false);

         
    }

    // Update is called once per frame
    void Update()
    {
        livesText.text = "Hearts " + health;
        if (health <=1)
        thePlayer.gameObject.SetActive(true);
        if(health <=0)
        {
           gameOverScreen.SetActive(true);
           thePlayer.gameObject.SetActive(false);
        }
    }



    public void TakeLife()
    {
        health--;
        thePlayer.gameObject.SetActive(true);

    }

    private void RestartLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
   
}

The only thing not needed is my definition of PlayerMovement _thePM. I was trying to use parts of that script to fix issues with the GameManager and LivesManager, but that failed.

You’d think this system (hearts counter) would be easy to implement, turns out, far from that.

@[DrDemencio]( How to Fix Issue with GameManager and OnCollisionEnter2D functions? members/drdemencio.10777956/)

Luckily, there is no issue anymore with anything related to Colliders, so I decided to make this thread resolved. There still is a bug, but the extent to this issue is small, and would be best served under a different topic.

1 Like