- Home /
Bullet disappears for no reason
For some reason, sometimes when the player shoots the bullet is deleted immediately after shooting. It looks as if it is colliding with something so I debug.logged it but it doesn't seem to be hitting anything that would delete it.
This is the code for shooting
public float damage;
public float travelLimit;
public Rigidbody2D rb;
public GameObject player;
private void Update()
{
if(Vector2.Distance(transform.position, player.transform.position) >= travelLimit)
{
Destroy(gameObject);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
SpiderEnemyBehaviour spiderEnemy = other.GetComponent
<SpiderEnemyBehaviour>();
if(spiderEnemy != null)
{
spiderEnemy.TakeDamage(damage);
Destroy(gameObject);
}
if(other != null)
{
Debug.Log($"Bullet hit {other.name}");
}
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other != null)
{
Debug.Log($"Bullet hit {other.collider.name}");
}
}
Answer by LuigiDreemurr · Apr 28, 2020 at 05:31 PM
Does the bullet work some of the time? If so is it possible that its hitting the player or another bullet?
This is also on the bullet correct? You have a distance checker for the bullet to the player, check to see if all the variables are assigned, if not it could be thinking that its farther than it is and be destroying itself. Put a unique debug at each possible destroy point to find which one is triggering it. Good luck!
The bullet works most of the time but even when it is working, the debug says that it is hitting the player. The script is on the bullet and i put a debug that outputs the position of the bullet when it was destroyed and there seems to be nothing wrong with it
I ran into this before, Later i found out that the bullet spawning object i set for the bullet to spawn into on fire action was too close to the player head so i pushed the object forward a bit and it was the problem, it was hitting the player, make sure if thats the case by debug logging the name of the object that is colliding with the bullet ins$$anonymous$$d of the position.
If that is the problem, then you have two options: 1 - you push the object for instantiating the bullet further from the player (IF that's the way you set the bullet to spawn) 2 - exclude the player by a tag or a layer or even the name.
or maybe you just set it to distroy too early after spawning.
I increased the trace limit by a bit and that managed to fix it