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
Here is the Bullet script;
using System.Collections;
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!
Update
! – derHugoShoot
method on the bullet itself? Shouldn't it rather be on the spawner and you shoot/instantiate a bullet when pressing space? – derHugobullet
instance from the scene -> don't! You rather want to use an actual prefab asset .. otherwise you can't instantiate something that has been destroyed ;) – derHugobullet
is destroyed and you try to use it as parameter forInstantiate
.. which means as said you are using an actual scene object as original but you rather want to create a prefab from it and use that one instead – derHugo