Gun Turret Script. Help with distance C# Script

Hey guys I’m going to try and be as specific as can be as I’m completely new to C# Scripting. I’m trying to make a Gun Turret shoot at the play which is all sorted. But I’m having problems, I need to set 2 different distances one for the turret to start shooting and the other to start an alarm.
Every time I set the distance for example the turret to shoot at the player 10 meters away from the turret. But it just shoots regardless if I set the distance. Here’s the script below

using UnityEngine;
using System.Collections;

public class Turret : MonoBehaviour
{

public Transform target;
public float distance;
public float alarmRange;
public float firingRange;
public TurretFiring turretFiring;

void Update () 
{
	transform.LookAt (target);
	distance = Vector3.Distance(transform.position, target.position);
	if(distance <= firingRange)
	if(distance <= alarmRange)
	{
		turretFiring.canFire = true;
		audio.Play();
	}
		else
		turretFiring.canFire = false;
		audio.Play();
	
}

}

Your if statements are malformed. That’s likely the main cause of your issues. This is the most basic of C-like syntax, so if you’re having trouble, I suggest looking at basic tutorials for JS, C, C++, C#, or Java, all of which use very similar syntax for all basic operations (though obviously, C# would probably be better, since you’re using it here).

The crux of the issue displayed is that the first if, distance less-than-or-equal to firingRange, has no brackets. That means that it affects only the next line. Unfortunately, the next line in this case is your other if. The second if does have brackets, so it includes everything within them.

The else statement suffers from a similar fate. With no brackets, it only applies to the first expression after it, setting canFire to false. Audio will always play.

So therefore, in English, what you are saying is:

If Distance is less-than-or-equal to FiringRange then, if Distance is ALSO less-than-or-equal to AlarmRange set canFire to true and play my audio. If Distance is not less-than-or-equal to AlarmRange but is still less-than-or-equal to firingRange, set canFire to false. Then, regardless, play my audio.

What you probably meant is:

 if(distance <= firingRange)
 {
     turretFiring.canFire = true;
     audio.Play();
 }
 else if(distance <= alarmRange)
 {
     turretFiring.canFire = false;
     audio.Play();
 }

There are more efficient ways to do that, but that should work fine.

Lastly, a minor quibble: After pasting code, select it all and click on the little 101010 button. It’ll avoid parts of it being outside the Code Block, such as the class definition and closing bracket in your question.