Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Unity Multiplayer [PUN] Getting an object to Destroy Itself.

Discussion in 'Multiplayer' started by dann96, Aug 6, 2015.

  1. dann96

    dann96

    Joined:
    Dec 6, 2014
    Posts:
    113
    Hello.

    I am currently making a health script that destroys the player when they die. However, It took me a while to realize that the way I setup the script makes it so when the player dies (regardless of whether they are the Master Client or not) it always destroys the master client's player object. How can I fix this?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MultiplayerHealthSystem : MonoBehaviour
    5. {
    6.     public float StartingHealthLevel = 100;
    7.     float CurrentHealthLevel;
    8.  
    9.     void Start()
    10.     {
    11.         CurrentHealthLevel = StartingHealthLevel;
    12.         if (GetComponent<MeshRenderer>())
    13.         {
    14.             GetComponent<MeshRenderer>().material.SetColor("_Emission", Color.red);
    15.         }
    16.     }
    17.  
    18.     void Update()
    19.     {
    20.         if (PhotonNetwork.isMasterClient)
    21.         {
    22.             Debug.Log("Is Master Client");
    23.         }
    24.     }
    25.  
    26.     [PunRPC]
    27.     public void TakeDamage (int amount)
    28.     {
    29.         CurrentHealthLevel -= amount;
    30.         Debug.Log(PhotonNetwork.playerName + " Recieved Damage: " + amount);
    31.      
    32.         if (CurrentHealthLevel <= 0)
    33.         {
    34.             Die();
    35.         }
    36.     }
    37.     void Die()
    38.     {
    39.         THAT ORIGINALLY CALLED IT
    40.         Debug.Log(PhotonNetwork.playerName + " Has died");
    41.         Cursor.visible = true;
    42.         Cursor.lockState = CursorLockMode.None;
    43.         if (GetComponent<PhotonView>().instantiationId == 0)
    44.         {
    45.             Destroy(gameObject);
    46.         }
    47.         else
    48.         {
    49.             if (PhotonNetwork.isMasterClient)
    50.             {
    51.                 PhotonNetwork.Destroy(gameObject);
    52.             }
    53.         }
    54.     }