x


Trying to get score counter...

I got my score counter to show up on my GUI Text, yet when I switch to another object with the same script its resets the score to zero. What can i change or add to stop it from resetting?

var speed = 5;
var buck = 100;
var deer = 10;
private var score : int = 0;
var ScoreBoard: GUIText;


function Update () {
    transform.position += Vector3.forward * Time.deltaTime * speed;
}

function OnMouseEnter () {
    Debug.Log("Hit");
    speed = 15;
    deer += 10;
    ScoreBoard.text = ("Score: ") + deer;
}   

function OnMouseExit () {
    Debug.Log("Safe");
    speed = 5;
}
more ▼

asked Sep 22 '11 at 01:52 AM

Beta_Artist gravatar image

Beta_Artist
1 14 15 15

What do you mean, 'switch to another object'? I wasn't aware that moving components around was exactly straightforward. If you mean putting another instance of the script on a different object, then of course the score will reset to zero- it's a private member of a different object!

Sep 22 '11 at 01:58 AM syclamoth
(comments are locked)
10|3000 characters needed characters left

2 answers: sort oldest

You can declare score as a static variable:

static var score : int = 0;

A static variable is created once at the program beginning, lives while the program is running and is unique: all script instances use the same variable. Non-static variables exist in each script instance and are independent of each other.

more ▼

answered Sep 22 '11 at 02:12 AM

aldonaletto gravatar image

aldonaletto
41.4k 16 42 197

(comments are locked)
10|3000 characters needed characters left

Wait. Are you attaching the same script to multiple objects? Because if you're doing that, this will treat each 'val deer' as different ones.

You'd need to setup a control script that acts as a global counter. This controller script can handle things like score keeping.

more ▼

answered Sep 22 '11 at 02:18 AM

Holynub gravatar image

Holynub
1 2 2 2

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5072
x665
x532
x273
x100

asked: Sep 22 '11 at 01:52 AM

Seen: 1326 times

Last Updated: Sep 22 '11 at 02:18 AM