I am new to using unity and I am still learning C#. So pls bear with me if the problem mentioned below may seem a little odd or easy to fix.
I am creating a project in order to try to shoot a bullet from a turret, and I have included a function in my bullet script that will destroy the bullet after it has crossed certain boundaries and a function in my bulletSpawner script to Instantiate the bullet if it is destroyed. For some reason whenever I play and shoot the bullet and it crosses the boundary, it doesn’t get cloned
Site
Here is the Bullet script;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
[SerializeField]
private float Power = 50f;
private Rigidbody2D myBody;
private SpriteRenderer sr;
private float posX;
private float posY;
private void Awake()
{
myBody = GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
}
void Update()
{
Shoot();
destroyBullet();
}
void Shoot()
{
if (Input.GetKeyDown(KeyCode.Space))
{
myBody.AddForce(new Vector2(Power, Power - myBody.gravityScale),
ForceMode2D.Impulse);
}
}
void destroyBullet()
{
posX = transform.position.x;
posY = transform.position.y;
if (posX > 100 || posX < -100 || posY > 100 || posY < -100)
Destroy(gameObject);
}
}//class```
Here is the BulletSpawner script
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletSpawner : MonoBehaviour
{
public Transform bullet;
void Update()
{
StartCoroutine(SpawnBullet());
}
IEnumerator SpawnBullet()
{
while (!GameObject.FindWithTag("Bullet"))
{
yield return new WaitForSeconds(3);
Instantiate(bullet);
}//while
}//Ienum
}//class```
Note: I have attached my Bullet Prefab to bullet in the inspector panel
Whenever the bullet is out of bounds, or gets destroyed, I get this error:
MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
I know it has been destroyed but I want to find a way to access it so that it can clone the bullet(which can be fired again, destroyed and so on...)
Please advise on what I can do to fix this code, or any alternatives in order to prevent such errors from happening in the future. Any feedback would be appreciated :) ...
Thanks in advance!