0

this is my code for the player spawn but I'm getting a null reference exception error.

public class PlayerSpawn : MonoBehaviour 
{
    public Transform playerSpawn;
    public Vector2 currentTrackPosition;
    public bool activeRespawnTimer = false;
    public float respawnTimer = 1.0f;
    public float resetRespawnTimer = 1.0f;

    void Start () 
    {       
        if(playerSpawn != null)
        {
            transform.position = playerSpawn.position;  
            Debug.Log(playerSpawn);
        }
    }
    
    void Update () 
    {
        if(activeRespawnTimer)
        {
            respawnTimer -= Time.deltaTime;
        }
        
        if(respawnTimer <= 0.0f)
        {
            transform.position = currentTrackPosition;
            respawnTimer = resetRespawnTimer;
            activeRespawnTimer = false;
        }
    }
    
    void OnTriggerEnter2D(Collider2D other)
    {
        //im getting the error messege at this position
        if(other.tag == "DeadZone")
        {
            activeRespawnTimer = true;  
        }

        if(other.tag == "CheckPoint")
        {
            currentTrackPosition = transform.position;
        }
    }
}

What is the problem? Thank you for the help.

Milan Egon Votrubec
  • 3,696
  • 2
  • 10
  • 24
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – CodeSmile Feb 16 '15 at 10:44

1 Answers1

1

Given the position you mention the null reference exception occurs, it appears as if either other or other.tag is null. Considering that OnTriggerEnter is only called when an actual object enters the trigger, I highly doubt that other is null, unless it's been destroyed prior to the method being called. In any case, it's better to be safe than sorry.

One simple solution would be the following:

void OnTriggerEnter2D(Collider2D other)
{
    if(other != null && other.tag != null)
    {
        if(other.tag == "DeadZone")
        {
            activeRespawnTimer = true;  
        }

        if(other.tag == "CheckPoint")
        {
            currentTrackPosition = transform.position;
        }
    }
}

If this still throws an exception, then it must be something else that's causing the problem, so let me know how this works out.

Steven Mills
  • 2,363
  • 26
  • 36