-1
\$\begingroup\$

It's simple turret rotating code. The problem is when the Player is destroyed by enemies, I get this error message below: "NullReferenceException: Object reference not set to an instance of an object LookAtPlayer.Start () (at Assets/Scrpits/Transform/LookAtPlayer.cs:15)".

I understand why I get this error, but somehow cannot solve it. All turret must look at the last position of the Player, I tried something but couldn't solve again.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAtPlayer : MonoBehaviour {

public float rotateSpeed = 2f;

private Transform player;
private Vector3 lookDir;

// Use this for initialization
void Start()
{
    player = GameObject.FindGameObjectWithTag("Player").transform;
}

// Update is called once per frame
void Update()
{
    if (player != null)
    {
        lookDir = player.position - transform.position;
        lookDir.y = 0f;

        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(lookDir), rotateSpeed * Time.deltaTime);
    }
}

}

\$\endgroup\$
1
  • \$\begingroup\$ Does this LookAtPlayer script is on each enemy GameObject and those enemies spawn at runtime? \$\endgroup\$ Mar 16, 2022 at 18:26

1 Answer 1

1
\$\begingroup\$

I am assuming that your enemies are spawning even after your player is destroyed thus it throws exception as it couldn't find one and you're directly accessing transform of null object.

// Use this for initialization
    void Start()
    {
        GameObject go = GameObject.FindGameObjectWithTag("Player");
        if(go != null)
        {
            player = go.transform;
        }
        
    }
\$\endgroup\$
1
  • \$\begingroup\$ Yes, it was as you said. Now I don't get the error. Thank you so much. \$\endgroup\$
    – Limbo
    Mar 16, 2022 at 18:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .