Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Respawn doesn't work :(

Discussion in 'Multiplayer' started by gingerbready, Aug 4, 2023.

  1. gingerbready

    gingerbready

    Joined:
    Mar 18, 2022
    Posts:
    1
    For some reason when one character dies the other one won't teleport back to their spawnpoint. If I did it correctly I also make sure that both of the players can't move so that they can be teleported. However, it still doesn't work. Moreover, when I press the Q key though it does work? It makes no sense...I did the If(IsHost) and If(IsClient) because my game only has 2 players so there are only one of each. Thanks for helping :) Also my code is kind of messy. and I also have a lot of documentation.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using Unity.Netcode;
    4. using UnityEngine;
    5. using Cinemachine;
    6. using UnityEngine.InputSystem;
    7. using Unity.Mathematics;
    8. using UnityEngine.UI;
    9.  
    10.  
    11.  
    12.  
    13. public class PlayerNetwork : NetworkBehaviour
    14. {
    15.  
    16.     [SerializeField] private CinemachineVirtualCamera vc;
    17.     [SerializeField] private AudioListener listener;
    18.     [SerializeField] private float rotationSpeed = 0.1f;
    19.     [SerializeField] private float accumulatedRotation;
    20.     private MyPlayerInput playerInput;
    21.     [SerializeField] float horizontalInput;
    22.     [SerializeField] float verticalInput;
    23.  
    24.     Vector3 moveDirection;
    25.     Rigidbody rb;
    26.     public Transform orientation;
    27.     [SerializeField] float moveSpeed;
    28.     public static bool BulletDestroy = false;
    29.     public static bool TakingDamage = false;
    30.  
    31.     public NetworkVariable<int> Health = new NetworkVariable<int>(1); //making a Network variable THESE ARE VERY IMPORTANT REMEMBER THIS
    32.     public ShootingVariable parent;
    33.     private bool Moving = false;
    34.     public static NetworkVariable<int> PlayerScore = new NetworkVariable<int>(value: 0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server); //IMPORTANT REMEMBER THIS
    35.     public Dictionary<ulong, bool> PlayerLogScore;
    36.     private int ScoreAmount;
    37.     private bool PlayerScoreIncrease;
    38.     public string Score;
    39.     private bool Spawnpoint;
    40.     public bool respawn;
    41.  
    42.  
    43.  
    44.  
    45.  
    46.     private void Start()
    47.     {
    48.         playerInput = new();
    49.         playerInput.Enable();
    50.         rb = GetComponent<Rigidbody>();
    51.         rb.freezeRotation = true;
    52.         TakingDamage = false;
    53.         Moving = true;
    54.         PlayerScore.Value = 0;
    55.         ScoreAmount = 0;
    56.         Score = ScoreAmount.ToString() + "Points";
    57.         NetworkManager.ConnectionApprovalCallback = ConnectionApprovalCallback;
    58.         Spawnpoint = true;
    59.         respawn = false;
    60.  
    61.  
    62.  
    63.  
    64.  
    65.     }
    66.  
    67.     void ConnectionApprovalCallback(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
    68.     {
    69.         response.Approved = true;
    70.         response.CreatePlayerObject = true;
    71.         response.Position = GetPlayerSpawnPosition();
    72.  
    73.     }
    74.  
    75.     Vector3 GetPlayerSpawnPosition()
    76.     {
    77.         return new Vector3(UnityEngine.Random.Range(-1000f, 1000f), 10, UnityEngine.Random.Range(-1000f, 1000f));
    78.  
    79.     }
    80.  
    81.     private void LookAround(Vector2 _input)
    82.     {
    83.         //calculting rotation amount from mouse delta * rotation speed
    84.         float rotationAmount = _input.x * rotationSpeed;
    85.         accumulatedRotation += rotationAmount; //accumulate rotation
    86.         transform.rotation = Quaternion.Euler(0, accumulatedRotation, 0);
    87.     }
    88.  
    89.     [ServerRpc]
    90.  
    91.     private void LookAroundServerRpc(Vector2 _input)
    92.     {
    93.         LookAround(_input);
    94.  
    95.     }
    96.  
    97.  
    98.     private void Update()
    99.     {
    100.  
    101.  
    102.         Vector2 MouseDelta = playerInput.Player.LookAround.ReadValue<Vector2>(); //to look around
    103.  
    104.         if (Input.GetKeyDown(KeyCode.T))
    105.         {
    106.             ScoreAmount += 1;
    107.             Debug.Log(ScoreAmount);
    108.         }
    109.  
    110.         if (ScoreAmount == 2)
    111.         {
    112.             Debug.Log("Player Hit Score");
    113.  
    114.         }
    115.  
    116.         if (Input.GetKeyDown(KeyCode.Q))
    117.         {
    118.             Debug.Log("Q pressed");
    119.             StartCoroutine(Spawning());
    120.         }
    121.  
    122.         if (Input.GetKeyDown(KeyCode.Escape))
    123.         {
    124.             Application.Quit();
    125.         }
    126.         if(respawn == true)
    127.         {
    128.             StartCoroutine(Spawning());
    129.             respawn = false;
    130.             /*if (IsHost)
    131.             {
    132.                 transform.position = new Vector3(15, 0, 0);
    133.                 respawn.Value = false;
    134.  
    135.             }
    136.  
    137.             if (IsClient)
    138.             {
    139.                 transform.position = new Vector3(-15, 0, 0);
    140.                 respawn.Value = false;
    141.             }*/
    142.         }
    143.  
    144.         /*if (Moving == false)
    145.         {
    146.             PlayerScoreIncrease = true;
    147.         }
    148.  
    149.         if (Moving == true && PlayerScoreIncrease == true)
    150.         {
    151.             ScoreAmount += 1;
    152.             PlayerScoreIncrease = false;
    153.             Debug.Log(ScoreAmount);
    154.         }*/
    155.  
    156.  
    157.         if (!IsOwner) return; //checks if the player that is pressing the keys is the owner of the character if not it uses another one
    158.         MyInput();
    159.         LookAround(MouseDelta);
    160.         Cursor.visible = false;
    161.         //Vector3 moveDir = new Vector3(0, 0, 0); //states the Vector3 as moveDir
    162.  
    163.     }
    164.  
    165.     void OnCollisonEnter(Collider other)
    166.     {
    167.         if (other.gameObject.tag == ("Ground"))
    168.         {
    169.             Debug.Log("Touching Ground");
    170.         }
    171.  
    172.  
    173.     }
    174.  
    175.     public override void OnNetworkSpawn() //make listener go on then give ownership of camera
    176.     {
    177.         if (IsOwner)
    178.         {
    179.             listener.enabled = true; //make listener
    180.             vc.Priority = 1;
    181.             //and give ownership of camera
    182.         }
    183.         else
    184.         {
    185.             vc.Priority = 0; //set variable for camera low (the higher the number the more priority)
    186.  
    187.         }
    188.         Health.Value = 100;
    189.         Moving = true;
    190.         //PlayerLogScore.Add(NetworkManager.LocalClientId, false);
    191.         if (!IsServer) PlayerScore.OnValueChanged += PlayerScoreChanged;
    192.         NetworkManager.ConnectionApprovalCallback = ConnectionApprovalCallback;
    193.         if (IsHost) //makes spawn points
    194.         {
    195.             transform.position = new Vector3(15, 0, 0);
    196.         }
    197.         else
    198.         {
    199.             transform.position = new Vector3(-15, 0, 0);
    200.         }
    201.  
    202.  
    203.     }
    204.     private void MyInput()
    205.     {
    206.         horizontalInput = Input.GetAxisRaw("Horizontal");
    207.         verticalInput = Input.GetAxisRaw("Vertical");
    208.     }
    209.  
    210.     public void PlayerScoreChanged(int PreviousValue, int newValue)
    211.     {
    212.         Debug.Log("changed it ");
    213.         //IncreasePlayerScore();
    214.     }
    215.  
    216.     private void FixedUpdate()
    217.     {
    218.         if (!IsOwner) return;
    219.         if (Moving == true)
    220.         {
    221.             MovePlayer();
    222.  
    223.         }
    224.  
    225.         if (Moving == false)
    226.         {
    227.  
    228.         }
    229.  
    230.  
    231.     }
    232.  
    233.  
    234.     IEnumerator Spawning()
    235.     {
    236.  
    237.         yield return new WaitForSeconds(.01f);
    238.         transform.position = new Vector3(1000, 1000, 1000);
    239.         yield return new WaitForSeconds(2);
    240.         SpawnPointsServerRpc();
    241.  
    242.         //Spawnpoint = true;
    243.  
    244.  
    245.     }
    246.     private void MovePlayer()
    247.     {
    248.         moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
    249.  
    250.         rb.AddForce(moveDirection.normalized * moveSpeed * 30f, ForceMode.Force);
    251.     }
    252.  
    253.     public void IncreasePlayerScore()
    254.     {
    255.  
    256.         PlayerScore.Value += 1;
    257.         Debug.Log(PlayerScore.Value);
    258.         Debug.Log(PlayerScore);
    259.  
    260.  
    261.     }
    262.  
    263.  
    264.     private void OnTriggerEnter(Collider other)
    265.     {
    266.  
    267.         if (other.gameObject.CompareTag("Bullet") && Moving == true)
    268.         {
    269.             //if (!IsServer) return;
    270.             Debug.Log("Hit");
    271.             //Health.Value -= 10;
    272.             Debug.Log(Health);
    273.             BulletDestroy = true;
    274.             Moving = false;
    275.             ScoreAmount += 1;
    276.             Debug.Log(ScoreAmount);
    277.             Spawnpoint = false;
    278.             //StartCoroutine(Spawning());
    279.             respawn = true;
    280.  
    281.  
    282.  
    283.  
    284.  
    285.  
    286.  
    287.  
    288.  
    289.             //IncreasePlayerScore();
    290.  
    291.             //parent.DestroyProjectilesServerRpc();
    292.  
    293.  
    294.         }
    295.     }
    296.  
    297.  
    298.  
    299.  
    300.  
    301.  
    302.  
    303.     /*if (GetComponent<Collider>().GetComponent<ShootingVariable>())
    304.         {
    305.             Debug.Log("Hit");
    306.             GetComponent<NetworkHealthState>().HealthPoint.Value += -10;
    307.            
    308.            
    309.         }*/
    310.  
    311.  
    312.  
    313.     // Start is called before the first frame update
    314.  
    315.  
    316.  
    317.     private void SetMyName(int Score)
    318.     {//call this as the local player
    319.         if (!IsLocalPlayer) return; //don't want others to change our name
    320.         ScoreAmount = Score;
    321.         ServerScoreServerRpc(ScoreAmount);
    322.     }
    323.  
    324.     [ServerRpc]
    325.     private void ServerScoreServerRpc(int Score)
    326.     { //called on the server's version of *this* player object
    327.         if (!IsLocalPlayer) ScoreAmount = Score;
    328.         ScoreForClientRpc(ScoreAmount);
    329.     }
    330.  
    331.  
    332.     [ClientRpc]
    333.  
    334.     private void ScoreForClientRpc(int Score)
    335.     {
    336.         if (!IsLocalPlayer && !IsServer) ScoreAmount = Score;
    337.     }
    338.  
    339.     private void ScoreCounter(string Scores)
    340.     {
    341.         if (!IsLocalPlayer) return;
    342.         Score = Scores;
    343.         SetPointsServerRpc(Score);
    344.     }
    345.  
    346.     [ServerRpc]
    347.     private void SetPointsServerRpc(string Scores)
    348.     {
    349.  
    350.     }
    351.  
    352.     [ServerRpc(RequireOwnership = false)]
    353.     private void SpawnPointsServerRpc()
    354.     {
    355.         SpawnPointsClientRpc();
    356.         Moving = false;
    357.         /*if (Spawnpoint == false && Moving == false)
    358.         {
    359.             transform.position = new Vector3(15, 0, 0);
    360.  
    361.         }
    362.         if (Spawnpoint == false && Moving == true)
    363.         {
    364.             transform.position = new Vector3(-15, 0, 0);
    365.         }*/
    366.         if (IsHost)
    367.         {
    368.             transform.position = new Vector3(15, 0, 0);
    369.             Debug.Log("Host Spawnpoint");
    370.             Moving = true;
    371.  
    372.         }
    373.  
    374.  
    375.     }
    376.     [ClientRpc]
    377.     private void SpawnPointsClientRpc()
    378.     {
    379.         Moving = false;
    380.         if (IsClient)
    381.         {
    382.             transform.position = new Vector3(-15, 0, 0);
    383.             Debug.Log("Client Spawnpoint");
    384.             Moving = true;
    385.         }
    386.         else
    387.         {
    388.             transform.position = new Vector3(-15, 0, 0);
    389.             Moving = true;
    390.         }
    391.     }
    392.  
    393.  
    394. }
    395.  
    396.  
    397.  
    398.  
    399.  
    400.