Reputation: 25
Basically, I have a bullet that gets shot from a gun on your player when you left-click. I can't specifically destroy the bullet that hits something, it destroys all of the bullets. :C I Assume A Good Fix For This Would Be To Make It Destroy Itself When Something Enters Its Trigger? I Don't Know How To Do That Though So If Anyone Can Help That Would Be Awesome! If You Want To See My Code Then You Can Just Ask.
this is on the thing that the bullet hits:
void OnTriggerEnter()
{
enemyHealth -= 2f;
ishit = true;
}
void OnTriggerExit()
{
ishit = false;
}
its setting a static variable to true and false. this is on the bullet:
void Update()
{
transform.Translate(Vector2.right * mspeed * Time.deltaTime);
bool hit = Enemy.ishit;
if (hit == true)
{
Object.Destroy(gameObject);
}
}
its using the static bool to destroy itself
Thanks!
Upvotes: 0
Views: 317
Reputation: 2173
Your best bet is calling Object.Destroy
on your bullet instance.
That will not destroy any other bullet.
If you mean to destroy the object associated with the current script, you can also call Object.Destroy
on this.gameObject
.
You can do this call OnCollisionEnter
.
Edit: Your problem is not that Object.Destroy
is destroying all bullets, but rather that every bullet destroys itself when one bullet hits.
You might want to try:
void OnTriggerEnter(Collider bullet)
{
enemyHealth -= 2f;
Object.Destroy(bullet.gameObject);
}
Upvotes: 1
Reputation: 13
You can have a script on "damageable" objects tracking collision and destroying the bullet that colides with it, or have the script on the bullet prefab destroying it self on collision.
Deppending on your game an alternative approach is to not instantiate bullets at all, if you are shooting bullets that move as fast as bullets really move, the player isnt going to see them anyway, you can use raycast to see if you are hitting something when the player shoots, make a sound, a muzzle flash, drop an empty cartdrige on the ground, and in case the player hits anything, instantiate some particles or whatever effect the bullet would have on the other end and be done with it...
Upvotes: 0