So I have a script attached to a GameObject that shoots bullets every second and i want to destroy those bullets once they’re off-screen.
I have this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyScript : MonoBehaviour {
public Transform bullet1;
public Transform bullet2;
// Use this for initialization
void Start () {
InvokeRepeating("ShootBullets", 1, 2);
}
// Update is called once per frame
void Update () {
}
void ShootBullets()
{
Transform flyingBullet1 = Instantiate(bullet1, bullet1.position, Quaternion.identity);
Transform flyingBullet2 = Instantiate(bullet2, bullet2.position, Quaternion.identity);
flyingBullet1.GetComponent<Rigidbody2D>().AddForce(Vector3.down * 200);
flyingBullet2.GetComponent<Rigidbody2D>().AddForce(Vector3.down * 200);
if(flyingBullet1.position.y < -5)
{
Destroy(flyingBullet1.gameObject);
}
}
}
But the bullets are not being destroyed. I tried it with DestroyImmediate as well but same result, bullets are not destroyed. I don’t have that much experience with Unity yet, so can someone tell me what I’m doing wrong? Thank you in advance!