Bullet clones will not be destroyed.
So i've been working on this mechanic for some time and finally got it to work, I just need the clones to destroy themselves after a few seconds (some bullets will run of into space). Here is my code, thanks!
using UnityEngine;
using System.Collections;
public class Turret3 : MonoBehaviour {
public GameObject bullet;
public GameObject cannonFlash;
private GameObject spawnPt;
// Use this for initialization
void Start () {
spawnPt = GameObject.Find ("oneSpawn");
cannonFlash.SetActive(false);
}
// Update is called once per frame
void Update () {
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Input.GetButtonDown ("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit Hit;
if (Physics.Raycast(ray, out Hit, 1000))
{
Debug.DrawLine(ray.origin, Hit.point);
GameObject newProjectile = Instantiate (bullet, spawnPt.transform.position, transform.rotation)as GameObject;
newProjectile.transform.LookAt (Hit.point);
newProjectile.rigidbody.AddRelativeForce(Vector3.up + Vector3.forward * 5000);
Destroy (newProjectile, 5);
print("" + Hit.point);
}
cannonFlash.SetActive(true);
}
if(Input.GetButtonUp ("Fire1"))
{
cannonFlash.SetActive(false);
}
}
}
Do you mean that line 45 is not working for all of your projectiles?
you might want to consider pooling? because creating and destroying so many objects can harm performance on mobiles sometimes i heard? here is an example of pooling bullets so it recycles them ins$$anonymous$$d of deleting them https://github.com/strangeioc/strangerocks
Answer by Tasarran · Mar 08, 2013 at 09:42 AM
Try putting a simple script on the bullet Prefab that only allows it to exist for a set time...
In other words, a script with a timer, that when it runs out, Destroy()s the parent GameObject.
If you need me to, I will write the script.
Hi, I have been searching for a long time. I have a function called fire, that shoots the bullets, and I want to destroy them if they pass out of view. But for some reason after it gets destroyed and i try to shoot again, it sends an error saying that the object is already destroyed. How do I fix this?
Answer by corriedotdev · Mar 23, 2014 at 10:00 PM
var lifeTime = 5.0;
function Awake ()
{
Destroy(gameObject, lifeTime);
}
Attach to the bullet, should only stay in the scene for 5 seconds here. Change the value as required ;)
It wont, its attached to the prefab which is a clone.. therefore would be deleted
Your answer
Follow this Question
Related Questions
destroy asset is not permitted to avoid data loss? 0 Answers
Cannot destroy the SphereCollider on Instantiated Objects 1 Answer
Script removing rigidbody component, NOT game object 1 Answer
I need help destroying a clone on function. 1 Answer
Destroy the first instantiated clone after 4 have been instantiated 1 Answer