- Home /
Other
How to do health thru network
I am making a simple shooting multiplayer game and I tried to set up the health and shooting script and it should work but it dose not seem to work.
heres the shooting script
using UnityEngine;
using System.Collections;
public class ShootingScript : MonoBehaviour {
public int speed = 5;
public Transform hold;
public Transform aim;
public bool aiming = false;
public float FireRate;
public GameObject Barrel;
public int dammage;
void FixedUpdate ()
{
if(Input.GetKey(KeyCode.Mouse1))
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, aim.position, step);
}
else
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, hold.position, step);
}
if(Input.GetKeyDown(KeyCode.Mouse0))
{
networkView.RPC("shoot",RPCMode.All);
}
}
[RPC]
void shoot()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit, 1000))
{
Health hitter = hit.transform.gameObject.GetComponent<Health>();
if(hitter != null)
{
networkView.RPC("hit",RPCMode.AllBuffered, 1);
}
}
}
}
heres the health script
using UnityEngine;
using System.Collections;
public class Health : MonoBehaviour {
public float hp = 2.0f;
[RPC]
public void hit(int dammage)
{
hp-=dammage;
if(hp<=0)
{
Network.Destroy(gameObject);
}
}
}
heres the scean
Answer by xt-xylophone · Mar 09, 2014 at 10:51 PM
What you are currently doing is when you click to shoot, you and all your 'copies' are shooting and then if each of those hit, it will send the message of a hit to everyone.
This has the problem of doubling up damage and things like that.
A few tips to change:
Dont need to RPC to yourself to shoot, just call 'shoot' locally.
You dont want your clones in other player's games to be able to deal damage too. Do an isMine on the shoot function before it RPCs the damage. Leave any effects you want to happen outside that check though so it looks like the clones are shooting, but its the owner who does the real calulations.
Only send the RPC of damage to the owner of the target hit rather than RPCMode.AllBuffered
Of course this is a non authoritative setup but it seems like thats what you are going for which is fine since its easier. But it does allow cheating very easily.
EDIT: Just realised you didnt say what was wrong. That ray cast with the -Vector3.down looks wrong, I assume you mean transform.forward? Right now the raycast goes straight up, not forward.
everything with the raycast works fine also there is only one of this script in the scean because the multiplayer deactivates all the scripts that are not its own. Im trying to get the raycast to send a message threw the network to the players script.
Follow this Question
Related Questions
Unet Not Syncing Health for Host 1 Answer
Why does the wrong enemy die with this raycast? C# 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Bullets flying in a random direction. 2 Answers