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);
}
}
}