Search Unity

All enemies taking damage rather than the single instance (csh

Discussion in 'Scripting' started by MrFlibble, Sep 18, 2017.

  1. MrFlibble

    MrFlibble

    Joined:
    Mar 3, 2014
    Posts:
    2
    Hey all,

    I've got a script which shoots a RayCast at an enemy, this is then meant to reduce a set amount of damage from the health script associated with that enemy. However currently, it is reducing the health of all enemies and I can't see why (from what I can tell I am telling it to damage only the instance of the object).

    Weapon Shooting script (You'll want to look at the "private void fire()" section:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. [RequireComponent(typeof(AudioSource))]
    7.  
    8. public class WeaponShooting : MonoBehaviour
    9. {
    10.  
    11.     private Animator animate;
    12.  
    13.     public int bulletsPerMag = 30;
    14.     public int maxBullets = 300;
    15.     public int bulletsLeft = 200;
    16.     public int currentBullets;
    17.  
    18.     public int shootDamage = 5;
    19.  
    20.     public float range = 50f;
    21.     public float fireRate = 0.1f;
    22.  
    23.     public Transform shootPoint;
    24.     public GameObject flash;
    25.  
    26.     float fireTimer;
    27.  
    28.     public AudioClip akshoot;      
    29.     public AudioClip akreload;
    30.     public AudioSource AudioSource;
    31.     public bool reloadisrunning;
    32.  
    33.     public Text ammoRemaining;
    34.  
    35.     public EnemyHealth enemyHealthScript;
    36.  
    37.  
    38.  
    39.     // Use this for initialization
    40.     void Start()
    41.     {
    42.  
    43.         animate = GetComponent<Animator>();
    44.         currentBullets = bulletsPerMag;
    45.         AudioSource = GetComponent<AudioSource>();
    46.         SetInitialReferences();
    47.  
    48.  
    49.     }
    50.  
    51.     void SetInitialReferences() {
    52.  
    53.         ammoRemaining = GameObject.Find("Ammo Remaining").GetComponent<Text>();
    54.  
    55.     }
    56.  
    57.  
    58.     // Update is called once per frame
    59.     void Update()
    60.     {
    61.  
    62.          if(Input.GetKeyDown(KeyCode.Mouse0))
    63.  
    64.         {
    65.             Fire(); // Executes the fire function if the mouse button is pressed or held.
    66.         }
    67.  
    68.         if (fireTimer < fireRate)
    69.             fireTimer += Time.deltaTime;
    70.  
    71.         if (currentBullets <= 0 || Input.GetKey(KeyCode.R) && reloadisrunning == false)
    72.         {
    73.             if (bulletsLeft >= 1 && currentBullets != 30)
    74.             {
    75.                 PlayReloadSound();
    76.             }
    77.             StartCoroutine(reloadWait());
    78.  
    79.         }
    80.  
    81.         ammoCountUI();
    82.  
    83.  
    84.     }
    85.  
    86.  
    87.     void ammoCountUI()
    88.     {
    89.         string bulletsLeftS = bulletsLeft.ToString();
    90.         string currentBulletsS = currentBullets.ToString();
    91.         ammoRemaining.text = currentBulletsS + "/" + bulletsLeftS;
    92.     }
    93.  
    94.  
    95.     void FixedUpdate()
    96.     {
    97.         AnimatorStateInfo info = animate.GetCurrentAnimatorStateInfo(0);
    98.  
    99.         if (info.IsName("Fire")) animate.SetBool("Fire", false);
    100.     }
    101.  
    102.  
    103.  
    104.     /// ----------------------------------- Firing the Gun -------------------------------------------------
    105.  
    106.  
    107.     private void Fire()
    108.  
    109.     {
    110.         if (fireTimer < fireRate) return; // This returns to the update
    111.  
    112.  
    113.  
    114.      [B]  if (currentBullets >= 1 && reloadisrunning == false)
    115.         {
    116.  
    117.             StartCoroutine(flashOn());
    118.             RaycastHit hit;
    119.  
    120.             if (Physics.Raycast(shootPoint.position, shootPoint.transform.forward, out hit, range))
    121.             {
    122.                 if (hit.rigidbody.gameObject.layer == LayerMask.NameToLayer("Enemy"))
    123.              
    124.                         {
    125.  
    126.                     enemyHealthScript = hit.collider.gameObject.GetComponent<EnemyHealth>();
    127.  
    128.                     if (enemyHealthScript != null)
    129.                     {
    130.                         enemyHealthScript.dtak47();
    131.                     }[/B]
    132.  
    133.  
    134.  
    135.                         }
    136.              
    137.      
    138.             }
    139.  
    140.             currentBullets--;
    141.             animate.CrossFadeInFixedTime("Fire", 0.01f); // Play the fire animation
    142.             animate.SetBool("Fire", true);      
    143.  
    144.  
    145.         }
    146.  
    147.  
    148.         fireTimer = 0.0f; // This resets the fire timer
    149.     }
    150.  
    151.     private void PlayShootSound()
    152.     {
    153.         AudioSource.clip = akshoot;
    154.         AudioSource.Play();
    155.     }
    156.  
    157.  
    158.     IEnumerator flashOn() //Muzzle Flash
    159.     {
    160.             flash.SetActive(true);
    161.             Debug.Log("flashOff");
    162.         PlayShootSound();
    163.         yield return new WaitForSeconds(0.15f);
    164.             Debug.Log("Timeup");
    165.             flash.SetActive(false);
    166.         if (Input.GetButton("Fire1"))
    167.         {
    168.             Fire();
    169.         }
    170.  
    171.     }
    172.  
    173.     /// ----------------------------------- Reloading the Gun -------------------------------------------------
    174.  
    175.     private void PlayReloadSound()
    176.     {
    177.         AudioSource.clip = akreload;
    178.         AudioSource.Play();
    179.     }
    180.  
    181.     IEnumerator reloadWait() //wait timer so that gun is not reloaded before the sound effectends
    182.     {
    183.         Debug.Log("wait start");
    184.         reloadisrunning = true;
    185.         yield return new WaitForSeconds(2f);
    186.         reloadisrunning = false;
    187.         Debug.Log("wait end");
    188.         Reload();
    189.     }
    190.  
    191.     private void Reload()
    192.     {
    193.         if (bulletsLeft >= bulletsPerMag)
    194.         {
    195.             if (currentBullets == 0)
    196.             {
    197.  
    198.                 bulletsLeft = (bulletsLeft -= bulletsPerMag);
    199.                 currentBullets = bulletsPerMag;
    200.             }
    201.  
    202.             else if (currentBullets != 0)
    203.             {
    204.                 bulletsLeft = (bulletsLeft - (bulletsPerMag - currentBullets));
    205.                 currentBullets = bulletsPerMag;
    206.             }
    207.  
    208.      
    209.         }
    210.  
    211.  
    212.         else if (bulletsLeft <= bulletsPerMag)
    213.  
    214.         {
    215.  
    216.             if (currentBullets == 0)
    217.             {
    218.                 currentBullets = bulletsLeft;
    219.                 bulletsLeft = 0;
    220.          
    221.  
    222.             }
    223.  
    224.             if (currentBullets != 0)
    225.             {
    226.  
    227.                 int dif = currentBullets + bulletsLeft;
    228.                 bulletsLeft = (bulletsLeft - (bulletsPerMag - currentBullets));
    229.                 currentBullets = dif;
    230.  
    231.             }
    232.  
    233.             if (bulletsLeft <= 0)
    234.             {
    235.                 bulletsLeft = 0;
    236.             }
    237.  
    238.             if (currentBullets >= bulletsPerMag)
    239.  
    240.             {
    241.                 currentBullets = bulletsPerMag;
    242.  
    243.             }
    244.  
    245.             if (currentBullets <= 0)
    246.             {
    247.                 currentBullets = 0;
    248.             }
    249.  
    250.  
    251.  
    252.         }
    253.     }
    254. }



    Health Script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnemyHealth : MonoBehaviour {
    6.  
    7.     public float health;
    8.     public int ak47damage = 10;
    9.     public EnemyHealth Instance;
    10.  
    11.  
    12.     // Use this for initialization
    13.     void Start()
    14.     {
    15.  
    16.         SetInitialReferences();
    17.         health = 100;
    18.  
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update()
    23.     {
    24.  
    25.         if (health < 1)
    26.         {
    27.             health = 0;
    28.         }
    29.  
    30.         if (health > 99)
    31.         {
    32.             health = 100;
    33.         }
    34.  
    35.     }
    36.  
    37.     void SetInitialReferences()
    38.     {
    39.         Instance = this;
    40.     }
    41.  
    42.     public void dtak47()
    43.     {
    44.         this.health -= ak47damage;
    45.     }
    46.  
    47. }
    Any help would be appreciated.
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    OK, I'm not sure on this, but your code basically looks all right, so I wonder if it's when you declare an instance for EnemyHealth. Maybe it's making a singleton. I don't know a lot about singletons so maybe that's a mile off. This is the code for a singleton, but the singleton code is sometimes hidden.

    Code (csharp):
    1.  
    2.     public static EquipmentManager instance;
    3.  
    4.     private void Awake()
    5.     {
    6.         instance = this;
    7.     }
    8.  
     
    Last edited: Sep 18, 2017
    Xepherys likes this.
  3. Xepherys

    Xepherys

    Joined:
    Sep 9, 2012
    Posts:
    178
    I think @fire7side is on the right track. You are setting up a single instance of EnemyHealth (singleton pattern) which is getting applied to all enemies.
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,713
    I do not think that is the problem. Actually, I cannot be sure how this script is affecting every enemy.
    I can say this, though.. your 'Instance' variable on the enemyscript doesn't appear to be doing anything that I can see. Unless that is being called somewhere I didn't see, you may as well remove it.

    An additional note: you'd be better off moving your health > 99 and < 0 to the method that takes damage, and deleting your update function , until there is actual code to run there.

    note: his declaration isn't 'static' , so it's not really a singleton in design. The variable instance, as a member (which isn't static), doesn't make a lot of sense, because you'd first have to find the instance, then accessing that member would be the same thing (you already had, with the instance).
     
  5. MrFlibble

    MrFlibble

    Joined:
    Mar 3, 2014
    Posts:
    2
    Thanks everyone, and thanks methos5k for the code tidy up, that makes a lot more sense.

    I'm still trying to rack my head around why on earth it's deducting from all scripts, as you mentioned it's not static and I'm retrieving the script component each time the RayCast hits and enemy.
     
  6. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    4,877
    I agree with @methos5k. I couldn't figure out from what was posted that anything was off in this script, so I thought I may have just overlooked something.

    Do you have any other scripts on the enemies? Or even anything else in the scene that may create issues.

    You may just have to start inserting debug statements and seeing what you're hitting, (see what hit.gameobject is for example). Insert one in the damage log, see how many times it prints out, etc. Best way to start tracking it down.
     
  7. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    What may be happening is in the weapon script you have:
    Code (csharp):
    1.  
    2.  public EnemyHealth enemyHealthScript;
    3.  
    If you dragged the script from project into that slot in the inspector, it might not change when you accessed it from the component. I'm not sure if that would even work, though.

    I would get rid of the instance code in EnemyHealth, it doesn't make sense.
     
    Last edited: Sep 19, 2017
unityunity