Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Player Kill Detector

Discussion in 'Netcode for GameObjects' started by bugattiguy527, Aug 18, 2023.

  1. bugattiguy527

    bugattiguy527

    Joined:
    Jul 7, 2023
    Posts:
    4
    I have spent the entire day tryna figure this out and I need some help and if you want I can PayPal you or whatever you a few dollars if you can help me out. I can send you a few my scripts for shooting but I just cannot figure out how to do this.

    Script for shooting the gun: https://pastebin.com/8ZpHhmaP

    Script that get spawned on every bullet that gets spawned:
    https://pastebin.com/nYaFudTy

    Script that deals with player health and hopefully kills:
    https://pastebin.com/Hzs0DMCg

    So you can take a look through my code. I just commented it so it should be fairly easy to understand my messy code but on the KillHealthManager script I want to make it so it detects who shot them. On line 49 is where I detect if the player got hit and what I want you to do is try to make it so it also tells who hit the player and then tell that player who hit them to increase their kill count variable by one if this makes sense. I provided the scripts I am using for shooting the gun, and the script that is on the bullet if you want to take a look at those. Thank you so much if you can help me and if not that is totally okay!
     
  2. lavagoatGG

    lavagoatGG

    Joined:
    Apr 16, 2022
    Posts:
    229
    I don't think it's a good solution but you can transfer information about who shot in the bullet, and then add one to his kill value on the server on hit.
    Something like this:
    Bullet code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Collections;
    5. using Unity.Netcode;
    6. using System;
    7.  
    8. public class Projectile : NetworkBehaviour
    9. {
    10.  
    11.     //The speed of the projectile
    12.     public float projectileSpeed = 150;
    13.  
    14.     //The size the projectile should be
    15.     public float scale = 0.35f;
    16.  
    17.     //the id of the shooter
    18.     public NetworkVariable<ulong> shooterId = new NetworkVariable<ulong>();
    19.  
    20.     //The game object for the projectile that spawns.
    21.     public GameObject projectile;
    22.  
    23.     // Destroys the bullet if it runs into a wall or something that isint a player.
    24.     void OnTriggerEnter(Collider collider)
    25.     {
    26.         if (IsServer)
    27.         {
    28.             if (collider.gameObject.tag == "Untagged")
    29.             {
    30.                 Destroy(projectile);
    31.             }
    32.         }
    33.     }
    34.  
    35.  
    36.     [ServerRpc (RequireOwnership = false)]
    37.     public void AddKillsServerRPC()
    38.     {
    39.         KillHealthManager[] list = GameObject.FindObjectsOfType<KillHealthManager>();
    40.         for (int i = 0; i < list.Length; i++)
    41.         {
    42.             if(list[i].id.Value == shooterId)
    43.             {
    44.                 list[i].kills++;
    45.             }
    46.         }
    47.     }
    48.  
    49.     public override void OnNetworkSpawn()
    50.     {
    51.  
    52.         base.OnNetworkSpawn();
    53.  
    54.         //Sets the projectiles speed on network spawn.
    55.         GetComponent<Rigidbody>().velocity = this.transform.forward * projectileSpeed;
    56.  
    57.         //Sets the scale of the projectile to the projectile scale.
    58.         projectile.gameObject.transform.localScale = new Vector3(scale, scale, scale);
    59.     }
    60. }
    61.  
    KillHealthManager code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Collections;
    5. using Unity.Netcode;
    6. using System;
    7. using TMPro;
    8.  
    9. public class KillHealthManager : NetworkBehaviour
    10. {
    11.  
    12.     // Max amount of health for each player
    13.     public int maxHealth = 120;
    14.  
    15.     // Range of the map for the player to spawn in
    16.     [SerializeField] private float positionRange = 70f;
    17.  
    18.     // How many kills a player needs to win the game
    19.     public int killsToWin = 20;
    20.  
    21.     //the id of the player:
    22.     public NetworkVariable<ulong> id = new NetworkVariable<ulong>();
    23.  
    24.     //only the server keeps track of the kills
    25.     public int kills;
    26.  
    27.     // Textbox for the text that shows who won the round
    28.     public TMP_Text winText;
    29.  
    30.     // Keeps track of how many kills this player has
    31.     private int playerKills = 0;
    32.  
    33.     // The name of the player
    34.     private string playerName;
    35.  
    36.     private void Update()
    37.     {
    38.         CheckHealth();
    39.     }
    40.  
    41.     public override void OnNetworkSpawn()
    42.     {
    43.         base.OnNetworkSpawn();
    44.         applyIdServerRPC(NetworkManager.Singleton.LocalClientId);
    45.     }
    46.  
    47.     [ServerRpc (RequireOwnership = false)]
    48.     public void applyIdServerRPC(ulong _id)
    49.     {
    50.         id.Value = _id;
    51.     }
    52.  
    53.     // Just checks the players health and kills them if its 0 or below
    54.     public void CheckHealth()
    55.     {
    56.         if (health.Value <= 0)
    57.         {
    58.             Die();
    59.         }
    60.     }
    61.  
    62.     // This is the health variable that is synced across the network
    63.     [HideInInspector]
    64.     public NetworkVariable<int> health = new NetworkVariable<int>(
    65.         value: 120,
    66.         NetworkVariableReadPermission.Everyone,
    67.         NetworkVariableWritePermission.Owner);
    68.  
    69.     public void OnTriggerEnter(Collider collider)
    70.     {
    71.         //Checks if the player has been hit by a object and checks if that object had the script projectile, signifying they have been hit by a bullet and will now be subracted 15 health.
    72.         if (collider.GetComponent<Projectile>())
    73.         {
    74.             Debug.Log("Player Hit");
    75.  
    76.             // Negates their health by 15.
    77.             health.Value -= 15;
    78.         }
    79.     }
    80.  
    81.     // The script that gets called when a player dies/health is under 0.
    82.     void Die()
    83.     {
    84.         //When a players health is 0 or under, this script will run which resets their health and teleports them to a random position
    85.         transform.position = new Vector3(Random.Range(positionRange, -positionRange), 0, Random.Range(positionRange, -positionRange));
    86.         Debug.Log("Player Died");
    87.         health.Value = 120;
    88.     }
    89.  
    90.     private void Start()
    91.     {
    92.         if(NetworkManager.Singleton.IsServer)
    93.         {
    94.             kills = 0;
    95.         }
    96.  
    97.         // This is just a service I am using to keep track of player names and the items they own. Dont worry about this. All its doing is getting the player name from Loot Locker and setting it as the player name variable.
    98.         LootLockerSDKManager.GetPlayerName((response) =>
    99.         {
    100.             if (response.success)
    101.             {
    102.                 Debug.Log("Successfully retrieved player name: " + response.name);
    103.                 playerName = response.name;
    104.             }
    105.             else
    106.             {
    107.                 Debug.Log("Error getting player name");
    108.             }
    109.         });
    110.     }
    111. }
    112.  
    Gun code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Collections;
    5. using Unity.Netcode;
    6. using System;
    7. using TMPro;
    8.  
    9. public class Gun : NetworkBehaviour
    10. {
    11.  
    12.     // How often you can shoot the gun
    13.     public float fireRate = 15f;
    14.  
    15.     // The prefab of the bullet
    16.     public GameObject projectile;
    17.  
    18.     // The position of the bullet
    19.     private Vector3 destination;
    20.  
    21.     // Where the bullet gets spawned from
    22.     [SerializeField] private Transform InistialTransform;
    23.  
    24.     // All of these should be pretty self explanitory
    25.     public int maxAmmo = 15;
    26.     private int currentAmmo;
    27.     public float reloadTime = 1f;
    28.     private bool isReloading = false;
    29.  
    30.     //The camera that the player sees through and the impact effect when the bullet hits something.
    31.     public Camera fpsCam;
    32.     public GameObject impactEffect;
    33.  
    34.     // The animator for reloading
    35.     public Animator animator;
    36.  
    37.     // Keeps track of when the player can shoot next
    38.     private float nextTimeToFire = 0f;
    39.  
    40.     // Makes sure that they start with a full mag.
    41.     private void Start()
    42.     {
    43.         currentAmmo = maxAmmo;
    44.     }
    45.  
    46.     // Makes sure they dont start reloading.
    47.     void OnEnable()
    48.     {
    49.         isReloading = false;
    50.         animator.SetBool("Reloading", false);
    51.     }
    52.  
    53.     // Checks some player stuff.
    54.     void Update()
    55.     {
    56.         if (isReloading)
    57.         {
    58.             return;
    59.         }
    60.  
    61.         if (Input.GetKeyDown(KeyCode.R) && IsOwner)
    62.         {
    63.             StartCoroutine(Reload());
    64.             return;
    65.         }
    66.  
    67.         if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire && IsOwner)
    68.         {
    69.             nextTimeToFire = Time.time + 1f / fireRate;
    70.             if (currentAmmo > -1)
    71.             {
    72.                 Shoot();
    73.             }
    74.         }
    75.     }
    76.  
    77.     // Reloads the gun
    78.     IEnumerator Reload()
    79.     {
    80.         isReloading = true;
    81.         Debug.Log("Reloading...");
    82.  
    83.         animator.SetBool("Reloading", true);
    84.  
    85.         yield return new WaitForSeconds(reloadTime - .25f);
    86.         animator.SetBool("Reloading", false);
    87.         yield return new WaitForSeconds(1f);
    88.  
    89.  
    90.         currentAmmo = maxAmmo;
    91.         isReloading = false;
    92.     }
    93.  
    94.     // Shoots the gun
    95.     void Shoot()
    96.     {
    97.         currentAmmo--;
    98.  
    99.         RaycastHit hit;
    100.         if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit))
    101.         {
    102.             Debug.Log(hit.transform.name);
    103.  
    104.             ShootProjectile();
    105.  
    106.             GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
    107.             Destroy(impactGO, 2f);
    108.         }
    109.     }
    110.  
    111.     // Starts the instantiating bullet process.
    112.     void ShootProjectile()
    113.     {
    114.         Ray ray = fpsCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
    115.         RaycastHit hit;
    116.  
    117.         if (Physics.Raycast(ray, out hit))
    118.         {
    119.             destination = hit.point;
    120.  
    121.         }
    122.         else
    123.         {
    124.             destination = ray.GetPoint(1000);
    125.         }
    126.  
    127.         //Starts the instantiating bullet process.
    128.         SpawnBulletServerRPC(InistialTransform.position, InistialTransform.rotation, NetworkManager.Singleton.LocalClientId);
    129.     }
    130.  
    131.     // This actually instantiates and spawns the bullet where I want.
    132.     [ServerRpc]
    133.     private void SpawnBulletServerRPC(Vector3 position, Quaternion rotation, ulong id, ServerRpcParams serverRpcParams = default)
    134.     {
    135.         //Instantiates the bullet
    136.         GameObject InstantiatedBullet = Instantiate(projectile, position, rotation);
    137.  
    138.         //Spawns the bullet through the network
    139.         InstantiatedBullet.GetComponent<NetworkObject>().Spawn();
    140.         StartCoroutine(addId(InstantiatedBullet, id));
    141.     }
    142.  
    143.     public IEnumerator addId(GameObject bullet, ulong id)
    144.     {
    145.         yield return new WaitUntil(() => bullet.GetComponent<NetworkObject>().IsSpawned );
    146.         bullet.GetComponent<Projectile>().shooterId.Value = id;
    147.     }
    148. }
    149.  
     
  3. bugattiguy527

    bugattiguy527

    Joined:
    Jul 7, 2023
    Posts:
    4
    Tysm! Il try this code once I am able to in a few hours. Thanks!