1 of 54

DMA 126

Behaviors & Scripting

2 of 54

Announcements

  • Homeplay #1 is cancelled 😿�
  • I am still in the process of fixing the ProBuilder…🙇‍♂️�link to the official documentation has been corrected.�
  • Rollaball complete package is fixed now too, if you were having errors when importing it.

3 of 54

Schedule For Today

  • Reading discussion (quick)
  • Scripting Intro
  • Demo of premade / Reference behaviors
  • Open work time + instructor project check-in (have sketches ready)

4 of 54

C# (Unity scripting language)

  • Not exclusive to Unity
  • C-like (syntax very similar to C,C++, Java)
  • Object oriented (“inheritance”, “polymorphism”, “classes”, don’t worry about this)
  • Full featured, modern (lots of features, and ways of doing things)

5 of 54

How would you describe what scripting is for?

6 of 54

How would you describe what scripting is for?

Scripting = getting the computer to do work for us.

7 of 54

Some Uses of Scripts

  • NPC behaviors (Chase the player)
  • Player Abilities (Jumping, opening doors, shoot…)
  • Randomly Generating Levels
  • Tracking Game state (Score, HP, Checkpoints)
  • Saving Progress
  • Cheats / Level skips
  • Processing art assets
  • Checking some online status
  • Tools

OK, a bit of dumb question.

Most of the time we want the game to ‘do’ something, or to ‘happen’, or we want a ’system’, ‘mechanic’, that usually involves some amount of scripting, programming.

8 of 54

(Aside) Scripting vs. Programming?

Scripting = programming

scripting implies you are programming at a higher level of abstraction, and interacting with a more complicated underlying system (like a game engine).

9 of 54

Scripts we’ve already made

  • PlayerController.cs
    • Rolling the ball
    • Disappearing collectibles when touched
    • incrementing a score
    • Displaying a score
  • Rotator
    • Rotates the object

10 of 54

Rules for script names:

  • NO SPACES!
    • Player Mover❌ �PlayerMover✅�
  • CANNOT START WITH A NUMBER!
    • 126LaserBlaster❌ �DMA126LaserBlaster✅�
  • ONLY ALPHANUMERIC, (and _) ALLOWED
    • NPCBr@!n❌ �NPCBrain✅�
  • Each word in the name should start with a capital letter, w/o underscores (pascal case)*
    • Launch_pad😑�LaunchPad✅

*your code will still work even if you break this last rule, but it is highly recommended that you follow.

11 of 54

Rules for script names:

  • Script Filename and class name must match!

12 of 54

Rules for script names:

Try to come up with a name that succinctly and clearly describes what you hope your script will actually do.

Rotator 👍(yup!)

PlayerController 😑… does a bunch of stuff besides “Control” the player.

Maybe would be better to separate out into…?

  • PlayerMover
  • PickupCollector
  • ScoreDisplayer

13 of 54

Anatomy of a Script

14 of 54

‘using’ statements

  • At the very beginning of the script
  • “Import” extra code, and let us use special features
  • Might be added automatically if use autocomplete

15 of 54

Comments ‘//’ or ‘/* .. */’

  • Can be used for informational notes, comments
  • Or to exclude some lines of code from execution

COMMENT SHORTCUTS:

CommentCTRL+(K then C) (Visual Studio) �CTRL+/ (Visual Studio Code)

Uncomment�CTRL+ (K then U)�CTRL+SHIFT+/

16 of 54

public class <class name> : MonoBehaviour {

MonoBehaviour is a sort of template that provides various functionality, and allows us to attach the script to objects in our scenes. We build our scripts on top MonoBehaviour

Class name

Class we’re building on top of (base class, or super class)

17 of 54

Class / Function / Variable

Methods / Functions��“Behavior”

Fields / Global Variables��“state, characteristics”

Class

contains…

18 of 54

Start() { ... }

  • Start is a function or method,
  • code that executes one time, when the object first activated �(usually when the game boots up)
  • You’ll do setup here

19 of 54

Update() { ... }

  • Called every frame of our game (usually 30-60 times a second, depending on your computer)
  • Place where we’ll do continuous actions (like checking for input, or dynamically moving/animating an object)

20 of 54

FixedUpdate ? LateUpdate ?

FixedUpdate()

tied to the physics system updates on separate cycle from regular Update()

LateUpdate()

In case we need to make sure some code is executed after some other scripts regular Update()

21 of 54

Fields/Variables

‘Containers’ to hold data, or information about the object.

Always have

  • type (the kind of data the container can hold)
  • And a unique name

22 of 54

Fields/Variables

  • Fields are put before between the first curly brace ‘{‘ and void Start()’� (*not 100% true)

23 of 54

Fields/Variables

1: ‘public’ or ‘private’�optional

3: Name

4: = initial value optional

2: Type

4: semicolon

24 of 54

Fields/Variables

Set the value of a variable with ‘=’, followed by the value you want set

Here were are assigning the attached rigid body into field ‘rb’ (from PlayerController.cs)

Here were setting count to be its starting value plus 1 (increasing it by one)� (from PlayerController.cs)

25 of 54

Fields/Variables

How do variables help us?

26 of 54

Fields/Variables:��Local Variables

  • Can also declare variables locally (in the braces {...} of a function
  • Let’s us keep each line shorter, and more legible��(Thing how much longer and confusing next line would be without using a local variable)

27 of 54

Methods/Functions

  • Methods/Functions are named snippets of code
  • Code to be executed is contained between and open and closed curly braces { ... } after the defintion�
  • Special functions like ‘Update’ and ‘OnTriggerEnter’ are executed automatically �(e.g. Update executes every frame of the game)�
  • We can also define and execute our own custom functions (SetCountText was an example from RollABall)�
  • Functions can also output data (void means output nothing)

28 of 54

Methods/Functions

6: Code goes here

1: Return type

Often void (nothing)

2: Name

3: parentheses

5: Curly braces

4: Argument Type + Argument name

Optional,

Any number of pairs

Each pair comma separated,

public/private

optional

29 of 54

Methods/Functions

  • To execute (call) a function, simply use the name of the function, followed by parentheses�

Executing ‘SetCountText’ in PlayerController.cs to update the score display text

30 of 54

Methods/Functions

  • If the function has any arguments, pass the values of these inside the parentheses.

Calling ‘SetActive’ on the collided pickup when collided.

Passing ‘false’ to turns off the game object

31 of 54

The primary things we do to achieve stuff in C#

  • Make new classes �(usually new Scripts inheriting from MonoBehavior)�
  • Add fields to those classes �(to track state, or refer to other object we want to manipulate)�
  • Add methods to classes �(some special ones executed by Unity like Update(), some custom ones we use for our own functionality)�
  • Change, and query the values of fields�(some from our own classes, some from unity build in classes)�
  • Execute methods of (both Unity built-in like GameObject.SetActive(), and custom)

32 of 54

How do we access a particular field or method?

33 of 54

How do we access a particular field or method?

For fields and methods we make ourselves, we can just type their name

34 of 54

Class / Function / Variable

Methods / Functions��“Behavior”

Fields / Global Variables��“state, characteristics”

Class

contains…

35 of 54

Class / Function / Variable

Methods / Functions

  • SetActive()
  • CompareTag()
  • GetComponent<>()

Fields / Global Variables:

  • Transform
  • Name
  • Layer
  • …�

GameObject

contains…

36 of 54

Class / Function / Variable

Methods / Functions

  • SetActive()
  • CompareTag()
  • GetComponent<>()

… and more

Fields / Variables:

  • Transform
  • Name
  • Layer

… and more�

GameObject

contains…

37 of 54

Class / Function / Variable

Methods / Functions

  • SetActive()
  • CompareTag()
  • GetComponent<>()

Fields / Global Variables:

  • Transform
  • Name
  • Layer
  • …�

GameObject

contains…

Methods / Functions

  • Rotate()
  • TransformPoint()
  • InverseTranformPoint()
  • GetChild()

Fields / Global Variables:

  • position
  • localPosition
  • rotation
  • eulerAngles
  • localScale
  • gameObject
  • name (again!?)…

Transform

contains…

Also a class

38 of 54

Class / Function / Variable

Methods / Functions

  • SetActive()
  • CompareTag()
  • GetComponent<>()

Fields / Global Variables:

  • Transform
  • Name
  • Layer
  • …�

GameObject

contains…

Methods / Functions

  • Rotate()
  • TransformPoint()
  • InverseTranformPoint()
  • GetChild()

Transform

contains…

Also a class

Fields / Global Variables:

  • position
  • localPosition
  • rotation
  • eulerAngles
  • localScale
  • gameObject
  • name (again!?)…

39 of 54

Class / Function / Variable

Methods / Functions

  • Rotate()
  • TransformPoint()
  • InverseTranformPoint()
  • GetChild()

Fields / Global Variables:

  • position
  • localPosition
  • rotation
  • eulerAngles
  • localScale
  • name (again!?)…�

Transform

contains…

Also a class

40 of 54

Class / Function / Variable

Fields / Global Variables:

  • position
  • localPosition
  • rotation
  • eulerAngles
  • localScale
  • name (again!?)…�

Methods / Functions

  • Normalize()
  • Scale

Fields / Variables:

  • x
  • y
  • z
  • magnitude
  • …�

Vector3

contains…

Also a class*

Methods / Functions

  • Rotate()
  • TransformPoint()
  • InverseTranformPoint()
  • GetChild()

Transform

contains…

*well, technically a struct

41 of 54

Class / Function / Variable

Methods / Functions

  • Rotate()
  • TransformPoint()
  • InverseTranformPoint()
  • GetChild()

Fields / Global Variables:

  • position
  • localPosition
  • rotation
  • eulerAngles
  • localScale
  • name (again!?)…�

Transform

contains…

Also a class

42 of 54

Class / Function / Variable

Fields / Global Variables:

  • position
  • localPosition
  • rotation
  • eulerAngles
  • localScale
  • name (again!?)…�

Methods / Functions

  • Reverse
  • ToUpper()
  • ToLower()
  • Replace()

Fields / Global Variables:

  • length�

String (text)

contains…

Also a class

Methods / Functions

  • Rotate()
  • TransformPoint()
  • InverseTranformPoint()
  • GetChild()

Transform

contains…

43 of 54

Class / Function / Variable

Methods / Functions

  • logCoolness()
  • resetPassword()

  • StartCoroutine()
  • StopAllCoroutines()

Fields / Global Variables:

  • coolness = 90009
  • password = “1234”�…
  • enabled
  • transform
  • name
  • gameObject�

OurFancyNewScript

contains…

Green = Stuff we get to make up.

44 of 54

Making a new script

Either use the ‘Add Component Button’ or right click in the ‘Project’ tab.

45 of 54

Accessing these in practice with ‘.’ (period)

Starting from ‘other’ type of ‘Collider’, we access its ‘gameObject’ (type GameObject), �and execute ‘SetActive(false)’ on it.

other(Collider) → gameObject (GameObject) → SetActive()

46 of 54

‘this’

  • ‘this’ is a special keyword, referring to the script itself,
  • If you type ‘this’ followed by a ‘.’ you can access any of the fields of methods available in the script.�(including a bunch of invisible stuff inherited from MonoBehaviour)

47 of 54

AutoComplete (aka intellisense)

After typing a ‘.’ the auto complete menu should pop-up, showing everything available for access, and often some documentation.

You can also force it to appear with CTRL+SPACE

48 of 54

Having AutoComplete issues on lab computers?

If your autocomplete isn’t working on a lab computer…

  • open Edit → Preferences → External Tools
  • Change your external code editor to ‘Visual Studio 2019…’
  • Close Visual Studio
  • Reopen by going to menu Assets → Open C# project

Change to ‘Visual Studio 2019’

Close visual studio and re-open

49 of 54

Let’s Try Making a new script using these concepts

How about a player-launcher that flings the player in a direction when collided with

50 of 54

Let’s Try Making a new script using these concepts

Let’s try to make something together (off the cuff)

Any ideas?

51 of 54

Can we make something even more general purpose?

52 of 54

Instructor Provided Modules

Download Unity Package

NOTES:

  • Where possible, written to to be legible, and not overly complicated. May have bugs and limitations. Please notify us if you encounter any issues.�.
  • Scripts assume PlayerController is unmodified from the Roll-a-Ball tutorial�
  • Most scripts assume you are not using compound colliders multiple colliders on the same object.

53 of 54

Helper Modules

LINK TO DOWNLOAD / INSTRUCTIONS

Depending on time, can demo and explain the scripts

54 of 54

Open Work Time + Checking in on sketches

  • The rest of the class period will be an open work period to work on your project 1.�
  • Sagan and I will meet with everyone individually for a quick check-in about your roll-a-ball ideas.�
  • If you have any urgent technical issues, but we may not be able to help until your turn, or after we have met with everyone.�
  • I am also available to answer questions after class.