- Home /
Problem with increasing a variable
I have a problem with increasing an integer variable (level) by one. I think, I know where the problem is, but I do not know how to fix it. I explain my problem in code:
Let's say, I have two classes, Game.js and Menu.js.
In menu class I have a detection for buttons, like play, score and so. After score button is clicked, I call a function from game class. The function increases my level variable (there is a line: level++), but it does not increase it by one, but by two times. It performs a given piece of code twice, but I clicked just one time.
Then I try to put the function in menu class, and there it performs just one time, if I wanna. Of course, in Hierarchy have game objects with both classes. Here is sample of code:
Menu.js
//declare the raycast objects here so we dont need to instantiate them each frame
private var ray : Ray;
private var rayCastHit : RaycastHit;
var game : Game; // instantiate class Game.js
var play : GameObject; // play button
var score: GameObject; // score button
var exit : GameObject; // exit button
function Start()
{
}
function Update()
{
var aniPlay : aniSprite = GetComponent("aniSprite");
if(Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast (ray, rayCastHit))
{
if(rayCastHit.transform.name == "playButton" && !variables.drawAbout)
{
Application.LoadLevel("GameScene");
}
if(rayCastHit.transform.name == "scoreButton" && !variables.drawAbout)
{
game.write();
}
// here is more button detections, but this is just a sample
}
}
}
Game.js
function Start()
{
// in my original code, I give here valus to variables
}
function Update()
{
}
function write()
{
// Here is the root of the problem, this log will be write twice, but I want to only one time,
// because I have here the level variable and this increase it twice, not one time
Debug.Log("this log will be write twice");
}
If I have given the function write() to class Menu.js, all have been right, but I can't give every funtion to one class, it would be such mess. Please, help me, I really do not know, how to increse the variable of another class via a function only once.
Do you have two $$anonymous$$enu scripts/objects for some reason?
Answer by JoaquinRD · Sep 14, 2013 at 03:35 PM
Sounds like you have two objects that each have a Menu.js script component. Both are calling the Game.write function when you click the score button.