Search Unity

Bug Simple Variable Modification Not Working

Discussion in 'Scripting' started by Aftermorrow, Mar 25, 2023.

  1. Aftermorrow

    Aftermorrow

    Joined:
    Dec 6, 2021
    Posts:
    1
    Hi, I am making a simple 2d fighting game and health will decrease on one character while not doing so on the other. While printing health (2 different tests) the broken player will post this: upload_2023-3-25_15-48-46.png
    and the working one will post this:
    upload_2023-3-25_15-50-33.png
    The only difference is the order in which they will show the health. My script is this:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using TMPro;
    4. using UnityEngine;
    5.  
    6.  
    7. public class PlayerCombat : MonoBehaviour
    8. {
    9.     bool iscollided = false;
    10.     public TextMeshProUGUI player1;
    11.     public TextMeshProUGUI player2;
    12.     int player1health = 100;
    13.     int player2health = 100;
    14.     public int playerNumber;
    15.  
    16.     void Update()
    17.     {
    18.         if (Input.GetButtonDown("FirePrimary"+playerNumber.ToString()) && iscollided)
    19.         {
    20.             AttackPrimary();
    21.         }
    22.         player1.text = player1health.ToString();
    23.         player2.text = player2health.ToString();
    24.     }
    25.  
    26.     void AttackPrimary()
    27.     {
    28.         if(playerNumber == 1)
    29.         {
    30.             player2health -= 5;
    31.         }
    32.         if(playerNumber == 2)
    33.         {
    34.             player1health -= 5;
    35.         }
    36.     }
    37.  
    38.     private void OnCollisionEnter2D(Collision2D collision)
    39.     {
    40.         iscollided = true;
    41.     }
    42.     private void OnCollisionExit2D(Collision2D collision)
    43.     {
    44.         iscollided = false;
    45.     }
    46. }
    47.  
    All my code is the same for both players; no errors appear in the editor.
     
  2. samana1407

    samana1407

    Joined:
    Aug 23, 2015
    Posts:
    227
    When you take a second player’s health, like here

    Code (CSharp):
    1. if(playerNumber == 1)
    2. {
    3.      player2health -= 5;
    4. }
    This does not mean that the second player’s health has changed in the script. After all, you simply change the private variable of one object, which does not affect the amount of health in the script of the second player.

    Most likely it will work if you make these variables
    public static
    to make them "common" for the class.