I'm trying to destroy cloned prefabs when they reach the bound on the x axis of a cube. But when the first clone is destroyed, an error occur, and the next appearing clone won't destroy.
Error:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. deploy.Update () (at Assets/deploy.cs:52)
This is the script attached to the cube:
public class deploy : MonoBehaviour
{
public GameObject starsPrefab;
private GameObject star;
public float respawnTime=40.0f;
Vector3 bsize,bmax,bmin,plane;
// Start is called before the first frame update
void Start()
{
StartCoroutine(starsWave());
Collider bCollider = this.GetComponent<Collider>();
bsize=bCollider.bounds.size;
bmax=bCollider.bounds.max;
bmin=bCollider.bounds.min;
//Vector3 plane=new Vector3(bmax.x-bmin.x,bmax.y-bmin.y,bmax.z-bmin.z);
}
private void spawnStar()
{
star =Instantiate(starsPrefab) as GameObject;
star.transform.position= new Vector2(bsize.x,Random.Range(-bsize.y,bsize.y));
}
IEnumerator starsWave()
{
while (true)
{
spawnStar();
yield return new WaitForSeconds(respawnTime);
}
}
void Update()
{
if(star.transform.position.x<bmin.x)
{
Destroy(star);
}
}
If I increase respawnTime
, the same error occurs; the first clone appears, it reaches the bound, it's destroyed, there's the same error, a second clone appear afterwards, it reaches the bound, it's destroyed, there's the same error,&hellip
It seems that Destroy() is applied to the last cloned star, how can I apply this to any cloned star?