- Home /
The question is answered, right answer was accepted
Unable to reduce health in my networked shooting script
Hi Everyone. I was working on a Networked project in which i have to shoot other players on the network. i am using two c# scripts one for shooting and other for health deductions.
ShootScript
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Player_Shooting : NetworkBehaviour
{
private int damage = 50;
private float range = 50;
[SerializeField] Transform camTransform;
private RaycastHit hit;
[Command]
void CmdTellServerWhoWasShot(string name, int dmg)
{
GameObject identifier = GameObject.Find (name);
identifier.GetComponent<Player_health> ().ReduceHealth (dmg);
}
void Update()
{
CheckIfshoot ();
}
void ShootHim()
{
if (Physics.Raycast(camTransform.TransformPoint(0,0,0.5f), camTransform.forward,out hit,range))
{
Debug.Log (hit.transform.tag);
if (hit.collider.tag == "Player")
{
string uniqueID = hit.transform.name;
CmdTellServerWhoWasShot (uniqueID, damage);
}
}
}
void CheckIfshoot()
{
if (!isLocalPlayer)
{
return;
}
if (Input.GetButtonDown("Fire1"))
{
ShootHim();
}
}
}
HealthScript
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Player_health : NetworkBehaviour
{
[SyncVar (hook="IfHealthChanges")] private int pHealth=200;
private Text healthText;
void Start ()
{
healthText = GameObject.Find ("Health_text").GetComponent<Text> ();
SetHealth ();
}
void Update ()
{
}
void SetHealth()
{
if (isLocalPlayer)
{
healthText.text ="Health : "+ pHealth.ToString ();
}
}
public void ReduceHealth(int dam)
{
pHealth -= dam;
}
void IfHealthChanges(int health) //the Hook Function
{
pHealth = health;
SetHealth ();
}
}
But, whenever i am shooting player remains constant at 200. I am not able to find the problem. Please Help
Answer by LK84 · Jan 05, 2017 at 06:29 PM
I haven't look through your whole code, but this doesn't look right:
void CmdTellServerWhoWasShot(string name, int dmg)
Try passing the NetworkInstanceId instead (unique identifier for all GameObject with NetworkIdentity attached on all clients and server):
[Command]
void CmdTellServerWhoWasShot(NetworkInstanceId Id, int dmg)
{
GameObject identifier = NetworkServer.FindLocalObject(Id);
identifier.GetComponent<Player_health> ().ReduceHealth (dmg);
}
And call it like this: CmdTellServerWhoWasShot (hit.GetComponent<NetworkIdentity>().netId, damage);
This presumes of course that the hit collider game object has a network identity
thanks @L$$anonymous$$84, your suggestion also works nicely.
Follow this Question
Related Questions
FPS shooting 1 Answer
problem with scripting 1 Answer
Random Raycast inside crosshairs 1 Answer
Arrow not shooting the in right orientation 0 Answers
Problem in Shooting Accuracy 0 Answers