Skip to content

Lesson 9

Your first script

A script is code that tells a GameObject what to do. Write one that makes a sprite move.

15 minDraft

Draft lesson: nobody has followed it from start to finish in the editor yet, so a step may not match what you see.

Video coming soon

We are making a video for this lesson. For now, follow the steps below!

In this lesson you will

  • Know what a script is
  • Make a script and open it
  • Write code that moves a sprite

What is a script?

A script is a list of instructions for a GameObject. Like a recipe!

1. Make a script

  1. Click your sprite.
  2. Click Add Component.
  3. Type Mover in the search box, and choose Create script "Mover".

2. Open it

Go to the Code tab and open Mover. Some code is already there.

Picture coming soonA new script in the Code tab

3. Make it move

Find this line:

update(args: NUpdateArgs): void { }

Change it to this:

update(args: NUpdateArgs): void {
  this.mTransform.position.x += 100 * args.dt;
}

Press Ctrl + S to save. Go back to Design and press Play. Your sprite slides to the right!

How does it work?

  • update runs every frame. That is many times every second!
  • this.mTransform is the GameObject's Transform.
  • position.x += ... moves it a little to the right, every frame.
  • args.dt is the time since the last frame. With it, the sprite moves 100 pixels every second, on fast and slow computers.

The parts of a script

PartWhen it runs
initialize()Once, when the game starts
update()Every frame
destroy()When the game stops

Try this

  • Change 100 to 300. Faster!
  • Change += to -=. Which way does it go now?
  • Make it move on y too.

Learn more

JavaScript, the basics Variables, choices and functions. A short page from MDN.Opens in a new tab

Try it here

Coming soon

Your mission

Change the number in the script, press Play, and make the sprite go faster.

Soon, a small piece of the editor will be right here, so you can practise without leaving the lesson. For now, try it in the editor!