I'll use an example to explain, this score counter script is attached to an empty gameObject;
var scoreNumber = 0;
function OnCollisionEnter (hit : Collision) {
if(hit.gameObject.FindWithTag("enemy"))
scoreNumber += 10;
}
function OnGUI () {
GUI.Label (Rect(50,50,80,50), "Score: " + scoreNumber);
}
But I don't need that script to work for the empty gameObject, it needs to work for the payers laser. And if I attach it to the laser then of course the script dies when the laser does, and my GUI disappears. So what I'm wondering is if in the beggining of the collision script, if I could do something like
Slightly longer answer: there's pretty much always a way to access whatever game object, script, or variable you need to access; it's usually a simple matter of acquiring the necessary references using whatever method is most appropriate (the aforementioned link described several methods you can use).
Also note that this:
if(hit.gameObject.FindWithTag("enemy"))
Doesn't do what I'm guessing you think it does. I'm guessing you probably want this:
Is both syntactically and semantically meaningless, as far as I can tell. If there's something in particular you're trying to accomplish here, you might try describing it in words rather than guessing at the code.
Can I reference a gameObject in a script attached to a different gameObject?
Yes. You can access a GameObject of a script (assumed to be called "target" in this example), that is placed on another game object.
// Get some game object by any means, in this example we use GameObject.Find.
var otherGameObject = GameObject.Find("Other");
// Obtain the script that hold a reference to the GameObject you want.
var otherScript = (YourScript)otherGameObject.GetComponent("YourScript");
// Here you are.
var target = otherScript.target;
For your concrete example shown to us, you could create the GUI on one game object and have the lasers update the gui. Note that I will simplify some of the code involving the hit test that is redundant.
function OnCollisionEnter (hit : Collision)
{
if (hitTarget)
{
var score = GameObject.Find("Score");
var scoreScript = (ScoreScript)score.GetComponent("ScoreScript");
scoreScript.total += 10;
}
}
Another easy approach you can take is to have a static member that everyone can access directly.
function OnCollisionEnter (hit : Collision)
{
if (hitTarget)
{
// here, total is a static variable of ScoreScript.
ScoreScript.total += 10;
}
}
ScoreScript should then only have a variable that it uses to display score at all times, regardless if lasers are firing or not.