Destroy object

Hi
I want destroy object “bullet” after it reaches a distance:
using UnityEngine;
using System.Collections;

public class Shooter : MonoBehaviour {

public Rigidbody bullet;
public float power = 1500f;
public float moveSpeed = 2f;
public float range = 1f;

private float distance;

	void Update () {
	
	float h = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
	float v = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
	transform.Translate(h, v, 0);
		if(distance >= range){
	Destroy(bullet);}
	
	if(Input.GetButtonUp("Fire1"))
	{
	
	Rigidbody instance = Instantiate(bullet, transform.position, transform.rotation)as Rigidbody;
	Vector3 fwd = transform.TransformDirection(Vector3.forward);
	instance.AddForce(fwd * power);
	
	}
		distance += Time.deltaTime * moveSpeed;
	}
}

application does not respond to the code:

if(distance >= range){
    Destroy(bullet);}

2 Answers

2

You’ve not set distance to zero anywhere in your code. Maybe this should be done in Start().

Your going about this wrong. You need two scripts. One on the gun that actually does the instantiating of the bullet prefab. The other on the bullet prefab to do the time or distance based destruction. Trying to run both in the same script is possible, but more complicated.

I added in two separate scripts and it worked, thank you.