How do I make a global variable?

#1

I’m making a 2-octave piano, and I want to let the user both click the key and be able to press the keys on the keyboard (“tab” through “backslash” and “1” through “delete”).

One question is whether I can tell it to do something when tab and delete are pressed, and how.

My other concern is how to make a global variable. I want to make a variable called “file” and assign it to “PianoC3.wav” in “Default” to make it global. That way, in both Mousepressed and Keypressed, I don’t have to change it twice. However, it says “file is not defined” in “Default” even though that’s where I assigned it with “var file = ‘PianoC3.wav’;”. Is there something wrong with this, or is this another one of those “fill is not defined” things that I posted a while ago?

0 Likes

#2

Hey there!

One thing you can do if you want variables to be accessible between scripts is to add it to “this”., as in:

this.file = PianoC3.wav;

Then, you’ll be able to access this.file in mousepressed and keypressed!

Let me know if this works for you!

1 Like

#3

Thanks for helping me with that! I don’t have anymore time today, but I’m gonna try it out tomorrow.

0 Likes

#4

It doesn’t seem to work. It says that “PianoC3 is not defined” even though I used the same thing you showed.

0 Likes

#5

Hey @awc95014,

Another thing you can try is storing the variable inside of the project.

writing something like project.myCustomVariable = 'myValue' should give you access to it everywhere in the project, even in other objects!

1 Like

#6

so i’m guessing myCustomVariable is the variable, and “myValue” is the value. How would I get back to the variable? would i say myCustomVariable or project.myCustomVariable?

0 Likes

#7

It doesn’t seem to work with the project.variable = value thing, it just keeps saying it’s undefined.

1 Like

#8

You can make a global variable by just doing:

someVar =valueHere;

You can access it anywhere in your project by
referencing its name, like:

alert(someVar);

You can do this anywhere in your project.
I’d recommend declaring your project’s global variables
inside the default function of the timeline frame.

It’s worked great for me.

0 Likes