Adding up instances of a variable across different objects?

So I’m trying to create a stealth game where the player is easier to be detected by the AI if he stands in the light. Therefore I have come up with a point system for measuring light based on light intensity, range, distance to the player and objects in the way. The script has a variable called “theDistance” which gets higher and higher the more light is on the player. The script looks like this and is applied to all lights in my scene:

#pragma strict

var thePlayersHead : Transform;
private var theDistance : float;

function Start () {
	thePlayersHead = GameObject.FindGameObjectWithTag("Head").transform;
}

function Update () {

	transform.LookAt(thePlayersHead);

	Debug.DrawLine(transform.position, thePlayersHead.position, Color.red);
	var hit : RaycastHit;
	if (Physics.Raycast(transform.position, transform.forward, hit))
	{
		if (hit.collider.gameObject.tag == "Head" && hit.distance < light.range)
		{
			//Debug.Log("Working");
			theDistance = (light.range/hit.distance-1)*light.intensity;
		}
		else
		{
			theDistance = 0;
		}
	}
}

This part is working great. I have trouble with adding up all of the lights though. On the player I want a script that has a variable called “lightOnPlayer” that = the sum of all “theDistance” variables from the different lights across the scene.
I tried sending it to the Players script usind Sendmessage though this wouldn’t allow me to separate the different versions so the result was a constantly rising number because it kept adding the same variables over and over. I then thought of using arrays though I can’t seem to get that to work either. I hope you have a good idea, thank you in advance! :slight_smile:

really, I would just do this. is it true you have a FIXED, KNOWN number of lights in the scene?

on a script attached TO YOUR HERO: let’s say the script is called HeroInfo.js for clatity.

var lightA:Light
var lightB:Light
etc
etc

function giveMeTheLightValueNow():float
    {
    var result:float;
    result = 0.0;
    result +=  your calculation lightA;
    result +=  your calculation lightB;
    result +=  your calculation lightC;
    etc
    return result;
    }

then, your AI (or whatever) can just call that at any time.

your AI would already have a variable pointing to HeroInfo.js

private var heroFacts: HeroInfo;
...
heroFacts = GameObject.Find( .. your hero ..).GetComponent<HeroInfo>;
...
theLightingFactor = heroFacts.giveMeTheLightValueNow();

If your lights are not just a fixed known set, just loop through them in some way in the function giveMeTheLightValueNow

(Really your lights should be “kept together” in an array or something, if you have some extremely novel situation where lights are being created and destroyed constantly or whatever. Anyway that’s irrelevant - in most situations just make a variable for each light as in the code fragment at the top.)

So it’s that simple!