Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Enemy Health doesn't update in build

Discussion in 'Scripting' started by luukbraijmakers, Jul 17, 2023.

Thread Status:
Not open for further replies.
  1. luukbraijmakers

    luukbraijmakers

    Joined:
    Feb 11, 2021
    Posts:
    7
    Hi everybody I have a problem. I make an FPS using Raycast, and when I test if the raycast damage the Enemies (who are prefabs) in the editor everything works out fine, but when I do the same in the build I get a massive update delay. I have to wait multiple seconds to see the enemy disappear. There are no frame drops/lag on my part, the rest of the code works as intended.

    Does somebody knows how to fix this?

    If you need to see for example my project settings or my build setting just say so, but I haven't changed anything.

    Script for enemy health (is on the enemy prefab):
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class EnemyHealthManager : MonoBehaviour
    7. {
    8.     public int currentHealth = 3;
    9.  
    10.     public void Damage(int damageAmount)
    11.     {
    12.         //subtract damage amount when Damage function is called
    13.         currentHealth -= damageAmount;
    14.  
    15.         //Check if health has fallen below zero
    16.         if (currentHealth <= 0)
    17.         {
    18.             //if health has fallen below zero, destroy it
    19.             Destroy(this.gameObject);
    20.         }
    21.     }
    22. }
    23.  
    Shooting script (Is on the player gameobject)
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using TMPro;
    6.  
    7. public class RaycastShooting : MonoBehaviour
    8. {
    9.     [Header("Weapon Values")]
    10.     public int gunDamage = 1;
    11.     public float fireRate = 0.25f;
    12.     public float weaponRange = 50f;
    13.  
    14.     [Header("Weapon Class")]
    15.     public bool useAmmo;
    16.     public bool automatic;
    17.     public bool isRifle;
    18.     public bool isSubmachinegun;
    19.     public bool isShotgun;
    20.  
    21.     [Header("Unity Values")]
    22.     public Camera fpsCam;
    23.     public Transform firePoint;
    24.     public TextMeshProUGUI ammoText;
    25.  
    26.     [Header("Player Detection")]
    27.     public float gunShotRadius = 20f;
    28.     public LayerMask enemyLayerMast;
    29.  
    30.     private WaitForSeconds shotDuration = new WaitForSeconds(0.07f);
    31.     private AudioSource gunAudio;
    32.     private LineRenderer laserLine;
    33.     private float nextFire;
    34.     private AmmoManager ammoManager;
    35.  
    36.     private void Start()
    37.     {
    38.         laserLine = GetComponent<LineRenderer>();
    39.         gunAudio = GetComponent<AudioSource>();
    40.         ammoManager = FindObjectOfType<AmmoManager>();
    41.     }
    42.  
    43.     private void Update()
    44.     {
    45.         if (automatic)
    46.         {
    47.             if (Input.GetButton("Fire1") && Time.time > nextFire)
    48.             {
    49.                 if(useAmmo)
    50.                 {
    51.                     if(ammoManager.subAmmo > 0 && isSubmachinegun)
    52.                     {
    53.                         Shooting();
    54.                     }
    55.                 }
    56.             }
    57.         }
    58.         if(!automatic)
    59.         {
    60.             if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
    61.             {
    62.                 if (useAmmo)
    63.                 {
    64.                     if (ammoManager.rifleAmmo > 0 && isRifle)
    65.                     {
    66.                         Shooting();
    67.                     }
    68.                     if (ammoManager.shotgunAmmo > 0 && isShotgun)
    69.                     {
    70.                         Shooting();
    71.                     }
    72.                 }
    73.                 else
    74.                 {
    75.                     //Pistol:
    76.                     Shooting();
    77.                 }
    78.             }
    79.         }
    80.         AmmoUI();
    81.     }
    82.  
    83.     private void Shooting()
    84.     {
    85.         //Reset the delay
    86.         nextFire = Time.time + fireRate;
    87.  
    88.         AmmoManager();
    89.         PlayerDetection();
    90.  
    91.         //Begin with the effects
    92.         StartCoroutine(ShotEffect());
    93.  
    94.         //The origin of the raycast sould be the middlepoint of the camera
    95.         Vector3 rayOrigin = fpsCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));
    96.         RaycastHit hit;
    97.  
    98.         laserLine.SetPosition(0, firePoint.position);
    99.  
    100.         //Shooting Code:
    101.         if (Physics.Raycast(rayOrigin, fpsCam.transform.forward, out hit, weaponRange)) //Out allows us to store additional information from a function, in addition to it's return type
    102.         {
    103.             laserLine.SetPosition(1, hit.point);
    104.  
    105.             EnemyHealthManager enemyHealth = hit.collider.GetComponent<EnemyHealthManager>();
    106.             EnemyStunned enemyStunned = hit.collider.GetComponent<EnemyStunned>();
    107.  
    108.             if (enemyHealth != null)
    109.             {
    110.                 enemyHealth.Damage(gunDamage);
    111.                 enemyStunned.Stun(true);
    112.             }
    113.         }
    114.         else
    115.         {
    116.             // If we did not hit anything, set the end of the line to a position directly in front of the camera at the distance of weaponRange
    117.             laserLine.SetPosition(1, rayOrigin + (fpsCam.transform.forward * weaponRange));
    118.         }
    119.     }
    120.  
    121.     private void AmmoManager()
    122.     {
    123.         if(isRifle)
    124.         {
    125.             ammoManager.rifleAmmo--;
    126.         }
    127.         if(isSubmachinegun)
    128.         {
    129.             ammoManager.subAmmo--;
    130.         }
    131.         if(isShotgun)
    132.         {
    133.             ammoManager.shotgunAmmo--;
    134.         }
    135.     }
    136.  
    137.     private void AmmoUI()
    138.     {
    139.         if (useAmmo)
    140.         {
    141.             if (isRifle)
    142.             {
    143.                 ammoText.SetText(ammoManager.rifleAmmo.ToString() + " / " + ammoManager.maxRifleAmmo.ToString());
    144.             }
    145.             if (isSubmachinegun)
    146.             {
    147.                 ammoText.SetText(ammoManager.subAmmo.ToString() + " / " + ammoManager.maxSubAmmo.ToString());
    148.             }
    149.             if (isShotgun)
    150.             {
    151.                 ammoText.SetText(ammoManager.shotgunAmmo.ToString() + " / " + ammoManager.maxShotgunAmmo.ToString());
    152.             }
    153.         }
    154.         else
    155.         {
    156.             ammoText.SetText("No Ammo Needed");
    157.         }
    158.     }
    159.  
    160.     private void PlayerDetection()
    161.     {
    162.         //Make a sphere, if an enemy collider is in the sphere make those enemies aggressive
    163.         Collider[] enemyColliders;
    164.         enemyColliders = Physics.OverlapSphere(transform.position, gunShotRadius, enemyLayerMast);
    165.  
    166.         foreach (var enemyCollider in enemyColliders)
    167.         {
    168.             //Alert the enemies in the sphere
    169.             enemyCollider.GetComponent<EnemyAwareness>().isAggro = true;
    170.         }
    171.     }
    172.  
    173.     private IEnumerator ShotEffect()
    174.     {
    175.         gunAudio.Play();
    176.         laserLine.enabled = true;
    177.  
    178.         //yield stops the IEnumerator, and then return the data from shotDuration
    179.         yield return shotDuration;
    180.  
    181.         laserLine.enabled = false;
    182.     }
    183. }
    184.  
     
    Last edited: Jul 17, 2023
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    But it sounds like you have a bug!

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
  3. luukbraijmakers

    luukbraijmakers

    Joined:
    Feb 11, 2021
    Posts:
    7
    Hi Kurt, thanks for your answer.

    The problem is not that the code doesn't work in the editor, but that it doesn't work in the build. The code works fine in the editor but when I build it, there are suddently large delays in my heath script, or the entire script doesn't work anymore. And sadly I can't debug in the build (as far as I know).

    So, do you know why that could happen? Is there anything in my build settings or my scripts that make this happen? If needed I can send you my build settings/project settings, make videos or send you some neccecary files.

    PS. Thanks for the code tags, didn't know how to apply those.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Yes, you have a bug.

    There's ten million different ways a program can change its behaviour based on environment.

    Those reasons are irrelevant.

    You are interested in the reason (or reasons) yours is misbehaving.

    Time to start debugging to find out! We certainly don't know.
     
  5. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,326
  6. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    8,955
Thread Status:
Not open for further replies.