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