Search code examples
c#unity-game-engine

Problems with spawning player after death


i'm trying to create spawner for my player but have some problems with it. That's my code below

public class GameManager : MonoBehaviour
{
    

    [SerializeField] private GameObject playerPrefab;
    private GameObject currentPlayer;
    [SerializeField] Vector2 respawnPoint;
    [SerializeField] private Text playerLivesText;
    static public bool playerAlive;


   

    private void Start()
    {

        playerLivesText.text = Player.playerLives.ToString();
        playerAlive = true;

    }

    

    private void Update()
    {
        
        LoseGame();

        if (!playerAlive) 
        {
            RespawnPoint();
            
        }
    }

    private void RespawnPoint()
    {
       if(playerPrefab != null)
       {
            playerPrefab = currentPlayer;
            currentPlayer = Instantiate(playerPrefab, respawnPoint, Quaternion.identity);
            playerAlive = true;
       }
       
       
    }

I expect that this code will work like , when player died he will be respawned on respawnPoint but insted this , PlayerPrefab always missing in the inspector and Unity can't respawn my player. Because i have "Missing Reference" error, ArgumentException: The Object you want to instantiate is null or nothing happening but player still not respawning. I can't understand how i can assign my player again in player prefab after his first death.


Solution

  • you must delete this line: playerPrefab = currentPlayer; and make sure you set playerPrefab field in the inspector with the prefab from the Project Window, not the prefab from the Hierarchy.