Determining if character is in line of sight?

I'm building a basic 2D stealth game and I want to determine if the guards can see the character. Now the character can hide behind things too so I basically need to determine if the character is in the guards line of sight.

Does anyone know of an easy way to do this?

Thanks in advance!

Use Physics.Linecast in combination with Vector3.Angle for things like this. You already know the positions of the guards and your character, so it's easier and faster to use a linecast rather than an array of raycasts. For example:

var fov = 60.0;
private var hit : RaycastHit;

function LineOfSight (target : Transform) : boolean {
    if (Vector3.Angle(target.position - transform.position, transform.forward) <= fov &&
            Physics.Linecast(transform.position, target.position, hit) &&
            hit.collider.transform == target) {
        return true;
    }
    return false;
}

The LineOfSight function returns true if the transform that you pass in is within the field of view specified by the public variable, and there's nothing between transform.position and the target transform's position. That's a bit crude since it only takes into account a single line between two transforms, and therefore it wouldn't account for things like someone's head being visible while his body is hidden. So you might want to expand on that depending on the level of realism you're going for.

Use Raycasting. A raycast is a line drawn out from a point, in a certain direction, which "stops" (and notifies the script) if it's hit something. You can create an array of raycasts in the line-of-sight of each guard, and if any of these raycasts hit the player, then the guard can see him.

If you need to I can draw a picture to help you understand what I'm talking about.