Retrieve a variable


If I create a simple variable to load my page like this
var clickbutton1=0;

How can I retrieve this data and use it when I use a new javascript function when I click on a button. I have been trying for hours but I can not retrieve my variables that I created when loading the scene.

thank you for helping me

It depends on where you made that variable; if you did it within a function (most common, as opposed to a top-level script tag), then it will not be global to other functions. The easiest way to make it a global is to put them in the window object. So your code would become:


And then if you wanted to use it, you’d just do for example:

console.log("the value is" + window.clickbutton1);

Note that if you are using multiple scenes, and you are making the declaration on scene load for your first scene and might go back to that, you should probably make sure that the variable will not be reset. You can do this via:

if(window.clickbutton1 == null) {
   window.clickbutton1 = 0;

This will only set it if it hasn’t been set before. Otherwise it will retain whatever value it has.

Thank you very much for this explanation. I will test and do some research on window syntax that I do not know yet. I am indeed novice in javascript.


I replied to this question in your “Variable on click button” post.