unity destroy object when out of screen code example
Example 1: in unity i want to destroy a gameobject when it hits the edge of the screen
void OnBecameInvisible() {
Destroy(gameObject);
}
Example 2: in unity i want to destroy a gameobject when it hits the edge of the screen
using UnityEngine;
using System.Collections;
public class CarDetection : MonoBehaviour {
private Camera mainCamera;
public Vector2 widthThreshold;
public Vector2 heightThreshold;
void Awake () {
}
void Update () {
Vector2 screenPosition = mainCamera.WorldToScreenPoint (transform.position);
if (screenPosition.x < widthThresold.x || screenPosition.x > widthThresold.y || screenPosition.y < heightThresold.x || screenPosition.y > heightThresold.y) {
Destroy (gameObject);
}
}
}