My bullets are occasionally flying through objects and I really can’t figure out why. I’m using raycasting as opposed to colliders. Strangely, the speed of the bullet doesn’t seem to stop this from happening, can anyone see anything wrong with my code?
using UnityEngine;
using System.Collections;
public class BulletBase : MonoBehaviour {
public const string BulletHit = "bullethit";
public const string BulletExplode = "bulletExplode";
public float speed = 10.0F;
public float lifeTime = 2.0F;
protected Transform _tr;
protected float _spawnTime = 0.0F;
private void Awake() {
_tr = transform;
}
public virtual void Start() {
_tr = transform;
_spawnTime = Time.time;
}
private void FixedUpdate() {
// Check for collisions
RaycastHit hit;
if (Physics.Raycast(_tr.position, _tr.forward, out hit, 1.0F)){
if(hit.transform){
Messenger<RaycastHit>.Broadcast(BulletBase.BulletHit, hit);
DestroyBullet();
return;
}
}
}
private void Update() {
_tr.position += _tr.forward * speed * Time.deltaTime;
if (Time.time > _spawnTime + lifeTime){
DestroyBullet();
}
}
public void DestroyBullet(){
ObjectPoolManager.DestroyPooled( gameObject );
gameObject.SetActiveRecursively(false);
}
}
Oh and you might want to do the life time test in the beginning of the function, with an early return if it was destroyed.
– StatementArgh, so obvious now I look at it! Thanks.
– anon87078182You've got clean code there, but I am curious as to why you get the transform in both Awake and Start? This is of course of little importance but I thought you want to tidy that up too. Nice code.
– StatementWell this snippet is actually an amalgamation of two classes (which is why Start() is virtual) , I have a base bullet class and a sub class which is unique for each different bullet type. Since I am using the Object Pool, I need to reset the transform as the Start() method gets called when the bullet is resurrected. I could probably do without the Awake method though, thanks for noticing :)
– anon87078182