How do I make a global variable?

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?

1 Like

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

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

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

Hey @BaronAWC,

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

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?

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

1 Like

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.

I’m having the same issue and the answers above didn’t work.

  1. I picked up the keyboard-controlled smile face from the built-in assets.
  2. I wanted to implement an accelaration effect so I removed

var speed = 7;

from the update section to the default or the load section and added

speed++

to the keystrokes.
I got the undefined speed variable error.