Jump to content
This site uses cookies! Learn More

This site uses cookies!

armedunity.com uses cookies to improve user experience.

By continuing to use this site, you agree to allow us to store cookies on your computer.

  • 0
Sign in to follow this  
raul21

How to make damage script

Question

Hello,i'm kind a new in programing and i hope can someone help me to make a damage script on my game,cause i can t figure out how. Here is my health script,and hope someone can help.

 

using UnityEngine;
using UnityEngine.Networking;

namespace S3
{


    public class PlayerHealth : NetworkBehaviour
    {
        public const int maxHealth = 100;
        [SyncVar(hook = "OnChangeHealth")] public int currentHealth = maxHealth;
        public RectTransform healthbar;

        public void TakeDamage(int ammount)
        {
            if(!isServer)
            {
                return;
            }

            currentHealth -= ammount;
            if(currentHealth <=0)
            {
                currentHealth = maxHealth;
                RpcRespawn();               
            }

        }

        void OnChangeHealth(int health)
        {
            healthbar.sizeDelta = new Vector2(health * 2, healthbar.sizeDelta.y);
        }

        [ClientRpc]
        void RpcRespawn()
        {
            if(isLocalPlayer)
            {
                transform.position = Vector3.zero;
            }
        }
    }
}

Share this post


Link to post
Share on other sites

1 answer to this question

Recommended Posts

  • 0

TakeDamage needs to be an rpc bc all copies of the character on each client needs to know it’s taking damage, at minimum, the the client that owns that’s object does.

 

the most common thing you see ppl doing is calling the damage rpc on all clients, checking if it isMine (the client owner), if it is, then deduct health and sync it to all clients. It’s a hair less efficient, but it works. You can also (I believe) only call the rpc on the owner and then sync the health on all clients, that way only the owner receives the initial call. Don’t know for sure but pretty sure you can it that way. But both approaches work just fine

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...