How to make sprites spawn in and disappear on screenbounds in unity

Viewed 184

I'm trying to create a game where asteroids spawn in and despawn when touching a screenbound, I've looked at many tutorials but these doesn't work for me or say I got something wrong in the code while the code seems to be fine, how do I make it so they spawn in at random and despawn when they touch the screenbounds?

Code I got for now:

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

public class asteroid : MonoBehaviour
{
    public float speed = 10.0f;
    private Rigidbody2D rb;
    private Vector2 screenBounds;


    // Use this for initialization
    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(0, -speed);
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));

    }

    // Update is called once per frame
    void Update()
    {
        if (transform.position.y < screenBounds.y)
        {
            Destroy(this.gameObject);
        }
    }
}
2 Answers

Try to check if the Renderer component is visible:

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

public class asteroid : MonoBehaviour
{
    public float speed = 10.0f;
    private Rigidbody2D rb;
    private Vector2 screenBounds;


    // Use this for initialization
    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(0, -speed);
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));

    }

    // Update is called once per frame
    void Update()
    {
        if (!GetComponent<Renderer>().isVisible)
        {
            Destroy(this.gameObject);
        }
    }
}

You can use this function:

void OnBecameInvisible()
{
    Destroy(gameObject);
}
Related