Hey all
I have a problem with my health script! I want it to change when i say and I have a void start so when the player joins the server their health goes to 500, but when they join and I look at the int in the hierarchy the health saids 0 and there is nothing i can do in update or anything to change it!! What is happening?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Health : NetworkBehaviour
{
public int Amount;
[SyncVar]
public int playerHealth = 500;
void start ()
{
Amount = 2;
playerHealth = 500;
}
void update ()
{
if (!isLocalPlayer)
{
return;
}
if (playerHealth == 0)
{
playerHealth = 500;
}
}
void OnTriggerEnter2D (Collider2D other)
{
//if (other.CompareTag("Player"))
//{
//print("ok it works");
//}
if (other.CompareTag("slash"))
{
print("Ouch mateoxD");
}
}
}
[CODE/]
as you can see I have tried a few diffferent methods to set the players health to 500
hey twoten I go the collision working xD its just needed to be a OntriggerEnter2D instead of OnTriggerEnter. Nothing had to be done over the server xD change syncvars from the server?
Instead of start use, override void OnStartLocalClient otherwise you can get weird behaviour when player with high ping join your game and the start function doesnt get called properly. And use a hook on your syncvar so your health is also synced with newly joined players. Like this:
[Syncvar(hook="OnHealthChanged")]public int PlayerHealth;
public override void OnStartClient() //This runs on all clients!
{
OnHealthChanged (PlayerHealth); //Call the function on all clients
}
public override void OnStartLocalPlayer() //This runs only on our game instance
{
PlayerHealth = 500; //Set the health on our client instance
CmdSendServerMyHealth (PlayerHealth); //Send the server our initial health
}
[Command]
void CmdSendServerMyHealth(int Myhealth)
{
PlayerHealth = Myhealth; //Set the health value on the server
}
public void OnHealthChanged(string newHealthValue)
{
PlayerHealth = newHealthValue; //Update the PlayerHealth variable on all clients
}
Luckily for you I was already working on something like this for my TBA asset I hope this helps you on your way.