Home > Mobile >  how to check if player has been destroyed
how to check if player has been destroyed

Time:09-02

in the game I am creating when the player dies I destroy that object and move to a different scene which simply says you died, however the camera follows the player, this creates an error when the player is destroyed as it can no longer follow the player I cannot think of how to scan to see if the player has been destroyed (from inside the cameras script)

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

public class CameraMotor : MonoBehaviour
{
    public Transform lookAt;
    public float boundX = 0.001f;
    public float boundY = 0.001f;

    private void LateUpdate()
    {
        Vector3 delta = Vector3.zero;

        //to check if inside the bounds on X axis
        float deltaX = lookAt.position.x - transform.position.x;
        if (deltaX > boundX || deltaX < -boundX)
        {
            if (transform.position.x < lookAt.position.x)
            {
                delta.x = deltaX - boundX;
            }
            else
            {
                delta.x = deltaX   boundX;
            }
        }

        //to check if inside the bounds on Y axis
        float deltaY = lookAt.position.y - transform.position.y;
        if (deltaY > boundY || deltaY < -boundY)
        {
            if (transform.position.y < lookAt.position.y)
            {
                delta.y = deltaY - boundY;
            }
            else
            {
                delta.y = deltaY   boundY;
            }
        }

        transform.position  = new Vector3(delta.x, delta.y, 0);
    }
}

CodePudding user response:

When the object is destroyed, it's components are destroyed too. So You can simply check if Transform object is null.

if (Target == null)
{
   Debug.Log("Object has destroyed");
}

CodePudding user response:

Check if lookAt is not null before looking at the player...

private void LateUpdate()
{
    if(lookAt != null){
        Vector3 delta = Vector3.zero;

        //to check if inside the bounds on X axis
        float deltaX = lookAt.position.x - transform.position.x;
        if (deltaX > boundX || deltaX < -boundX)
        {
            if (transform.position.x < lookAt.position.x)
            {
                delta.x = deltaX - boundX;
            }
            else
            {
                delta.x = deltaX   boundX;
            }
        }

        //to check if inside the bounds on Y axis
        float deltaY = lookAt.position.y - transform.position.y;
        if (deltaY > boundY || deltaY < -boundY)
        {
            if (transform.position.y < lookAt.position.y)
            {
                delta.y = deltaY - boundY;
            }
            else
            {
                delta.y = deltaY   boundY;
            }
        }

        transform.position  = new Vector3(delta.x, delta.y, 0);
    }
}
  • Related