I am currently creating a simple script for a pistol required in my college project, I have everything working apart from one of the visual effects, which when implemented causes odd behavior. What I am trying to achieve is to use a raycast to any object not in the water layer, then apply a particle effect at that point and a force if it has a rigidbody. All of this is working fine but after that I want to cast a line cast from the point the gun to the point the raycast hit and check for a water surface in-between, if there is one create a splash effect. Although this works as intended when I use this method if I shoot at a an object and there isn’t water between it and the gun, the weapon fires very rapidly without depleting any ammo and I can’t work out why.
The following function is called when the mouse button is pressed:
function Fire()
{
if(bulletsLeft==0)
return;
if(Time.time - fireRate > nextFireTime)
nextFireTime = Time.time - Time.deltaTime;
while(nextFireTime < Time.time)
{
FireOneShot();
nextFireTime += fireRate;
}
}
and the Fire one shot function is as follows:
function FireOneShot()
{
if(audio)
{
audio.Play();
audio.loop = false;
}
var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
//Test for hit
if(Physics.Raycast(transform.position, direction, hit, range, notWaterLayer))
{
//Apply force to any hit objects
if(hit.rigidbody && hit.collider.gameObject.tag != "Boat")
hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
//Apply Sparks
if(hitParticles)
{
hitParticles.transform.position = hit.point;
hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
hitParticles.Emit();
}
//Send damage to hit object
hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
if(Physics.Linecast(transform.position, hit.point, hit, waterLayer));
hit.collider.SendMessageUpwards("splash", hit.point, SendMessageOptions.DontRequireReceiver);
}
//Check for water
else if(Physics.Raycast(transform.position, direction, hit, range, waterLayer))
hit.collider.SendMessageUpwards("splash", hit.point, SendMessageOptions.DontRequireReceiver);
//Take 1 from the remaing bullets
bulletsLeft--;
//Register that the player shot this frame for muzzle effects
m_LastFrameShot = Time.frameCount;
enabled = true;
//Reload if you run out of ammo
if(bulletsLeft==0)
Reload();
}
Via comenting out various sections of the code I have found it is the Linecast itself causing the issue as when that line is removed the rest functions as I would hope it to.
Thanks,
Langy
Good spotted ;) That semicolon will change everything... Curly brackets aren't necessary, but yes, they usually help to spot such mistakes.
– Bunny83I cannot thank you enough, that one stray semi-colon (which I now feel incredibly stupid for not spotting) cost me a good hour of troubleshooting, fixed when I removed it, thanks again.
– Langynom