Un Flashcards
A sprite is
An image you imported to your game.
Note:
It is a bitmap, which means pixels and colors.
The z-index of game objects is stored under
order in layer
Note: Higher numbers are more visible
The core functions of game object scripts are
Start: Initialization game objects (ie RigidBody)
Update: meant for input checks
FixedUpdate: meant for creating physics movements
To make a variable from the script available in the inspector, type
public int myInt = 1;
c# sheet
To write a float, type
0.1f
To write a function, type public int MyFunc(int number1) { Console.WriteLine("I'm doing something..."); }
Remember to make an explicit declaration when declaring a variable List-GameObject> allSoldiers = new List();
C# uses angle brackets for Generic Type parameters, meaning when you need to pass in an uninstantiated type class.
To create a class, type class ClassName {}
Void functions
Do not return a value
To write a method that doesnt return anything, type
static void MethodName()
{}
The first mandatory method called in any script is
static void Main()
{}
To set the namespace, type
namespace NameSpaceName
{}
To convert a number string into an int, type
int.Parse(“10”)
types can also have
methods. e.g. int.Parse(“10”)
To create a while loop, type
while (varName == true)
{}
To create an if else, type if (varName == "string") {} else if (varName == "string") {} else {}
To make a loop restart back from the beginning, type
continue
To write a try/catch, type try {} catch(ExceptionName) {}
Variables are only inside
the curly brackets they were declared in
To convert a string to lower case, type
stringVar.ToLower()
The types that can hold decimals are
double, float
To cast a double into an int, type
(int)(10.0)
Note: Casting a number does not round it, it truncates.
“using” statements automatically
call the dispose function on the object after it is used
To initialize a list, type List = new List()
The difference between a list and an array is
You dont need to set the size of a list, but an array you do.
To make an array: int[]
To make a list: List
To initialize an int array with values, type List = new List {1,2,3,4,5} int[] varName = new int[5] {1,2,3,4,5} or var varName = new int[5] {1,2,3,4,5} or List = new List {1,2,3,4,5}
To initialize a dictionary in c#, type Dictionary dictName = new Dictionary(); Note: c# does not provide and empty list as the value even if the type is set to list
To add to a dictionary, type
dictName.Add(“key”, “value”)
To get a dictionary value by the key, type
dictName[“key”]
The static modifier is used to Make a function a class function instead of an instance function
public methods can be called by
anyone
private methods can be called my
only other functions inside the same class
To avoid having to write the namespace, type
using NameSpaceName
note: No ;
Namespaces can be
Nested multiple times
To enter the c# repl, type
csharp
A common compiler for c# is
mono
You can compile c# scripts using mono by typing
mcs ScriptName.cs
To write to the console, type
Debug.Log(“string”);
System.Console.Write(“string”);
System.Console.WriteLine(“string”);
To get input into the console, type
System.Console.ReadLine();
Edits you make while in play mode
get deleted when you unplay
A tileset is
an image with small sprites that you can drag to repeat
A box collider 2d is
a box drawn around a game object to give it a barrier that creates collision events
Note: There are other shape colliders
To listen for presses on the arrow keys, type
Input.GetAxis(“horizontal”)
Note: The value will return 1 if they press right and -1 if they press left
Input.GetAxis(“vertical”)
Note: The value will return 1 if they press up and -1 if they press down
Note: To get these numbers in a more snappy way, type
Input.GetAxisRaw(“…”)
The two ways to make an object move are
Change the transform.position of the game object
or
Add a force to a RigidBody2D
You can get premade assets
by googling “unity assets 2d”
To get the current position of a game object in it’s script, type
transform.position
To trigger animations from a script, type
animator = GetComponent()
animator.play(“animation_name”)
This eliminates the need for the visual UI
A vector is
….
To add a script to a game object from within a script, type
public GameObject myObject; // Or get and existing one
myObject.AddComponent();
To pan the editor
To zoom in the editor
option + mouse drag
control + option + mouse drag
To detect a click, type
if (Input.GetMouseButtonDown(0)) {
Debug.Log(Input.mousePosition);
}
To load an asset into a script, you must
create a folder directly under the assets fold called “Resources”
Place an asset in there
Load the resource ie
Resources.Load(“AC Player”) as RuntimeAnimatorController
Note: Do not include the “Assets/” or the file extension
The difference between GetComponent and AddComponent is
GetComponent gets a component that is already added to the object the script is on.
Note: returns null if component is not already added.
AddComponent is used to add a new component to an object.
Note: Calling multiple times will attach multiple instances.
When you add a new component to a game object, it returns
an instance of that component so you can alter its properties after
Rigidbody2D rb = newGameObject.AddComponent();
rb.gravityScale = 0;
It is easier to access a game objects transform object by
using the dot notation than instantiating
newGameObject.transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y)
rather than
Transform newGameObjectTransform = newGameObject.transform
Note: Do game objects automatically get a transform component?
To convert a mouse position to the position in the game, type
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
MyGameObject.transform.position = new Vector2(worldPosition.x, worldPosition.y);
It seems that if you add an animator component to a game object, you do not need to add to the sprite renderer a
sprite
To make a field in the inspector component show up as a dropdown
use an Enum value as the public variable type
For the game to listen to keyboard events,
the mouse must be hovering over the game window
To get the direction of an object thats moving, type
Vector2 currentDirection = (currentPosition-previousPosition).normalized;
To give an object some force when it is pushing, use
rigidBodyInstance.drag = 1
For the box collider, the difference between offset and size is
Size is the dimensions of the box, and offset is how far away you want
To get a game object instance by its tag, type
target = GameObject.FindGameObjectWithTag("Player"); Note: This is a class method, not instance
To sort a List, type
using System.Linq;
List sortedArray = anArray.OrderBy(item => Vector2.Distance(gameObject.transform.position, item.transform.position)).ToList();
The difference between Input.GetMouseButtonDown(0) and Input.GetMouseButton(0) is
GetMouseButtonDown returns true for one game loop iteration
GetMouseButton returns true the entire time a click is held
To get a touch position from the previous game loop iteration, type
touchInstance.deltaPosition
OnCollisionEnter2D is called when
a game objects collider has begun touching either another rigidbody or collider.
a Rigidbody object will automatically be
pulled downward by gravity, since a rigidbody gives objects physics.
If a Game Object does not need physics, it does not need a
RigidBody2D
The function animator.SetInteger(“parameterName”, 3) is
changing the value of the parameterName in the animation manager that the transitions are listening to.
OnCollisionStay2D stops running after a while even though there is still a collision because
the Rigidbody2D falls asleep for performance reasons and stops detecting collisions.
To have a game object destroy itself, type
Destroy(gameObject);
Note: It knows gameObject is a reference to itself.
A tag must exist in the list in the game UI before
you can add it to a game object in a script
HUD stands for
heads up display (ie fixed on viewport)
Canvas sheet
A canvas is
a game object that displays 2D UI elements in screen space (viewport) rather than game space.
To give it a background, you
add a UI -> Panel inside of it
When you add a canvas it gets sized enormously, but in play game mode it just fits to the screen.
A pivot point is effectively the center of an image so when you set its position to a coordinate, that is the point that will go there.
A pivot point is denoted by the light blue circle.
? If your UI element (ie button) uses a Rect Transform component, the way to translate it is to move both the sides of the rectangle. If you only move one side it will just stretch/shrink.
If you add a UI image to your project, it will automatically be inside a canvas. (Sprites go in game space, UI images go in screen space)
If you want to have a basic colored square in your canvas, add an image and it will be a white square.
To center a game object in the editor
double click it in the left panel hierarchy
Anchor point sheet
anchor points are like
stakes in the ground with strings connected to one of your blue corner dots, so if your anchor points are on all 4 corners, then any resize vertically or horizontally of screen will pull those corners and stretch your blue corner dots, but if they were clustered together 2 on the left and 2 on the right but the y was 0.5, then stretches vertically wont make them pull on your top and bottom corners.
When you change an anchor point of a UI object,
unity automatically changes its translation in the transform component to accommodate the new anchor points without moving where it was in the UI.
Under the anchors field, the min and max are the separate 4 corners of the anchor points.
min x is bottom left max x is bottom right min y is bottom left max y is top left (I assume top right is computed)
So if you don’t want any pulling on your corners, you need to put all the anchor points clustered in the center of your object.
For a heath bar (and many multi image objects), all the inner objects should have anchor points set to the corners of the parent object so that they scale in the same proportion to the parent. I supposed unless it might look weird like a photo.
Unity counts the x and y starting from the
bottom left
It seems the components you add to a game object in the UI become
available in the script’s environment under their component name lower cased. ie slider, rigidbody2d
It is good to use git with Unity because
sometimes there is no way to command z a bug
?To instantiate a new component into the script, type
private ComponentName componentInstance;
To to able to get different colors along a gradient based on a value from 0 to 1, type
public Gradient gradient;
gradient.Evaluate(0.5f)
The proper place for attributes is always in the script on
the game object they are most relevant to, since you can make any attribute public and accessible from other scripts or trigger events.
In C# to make a float alway positive, type
Mathf.Abs(-1.0f)
A delegate is a
function stored in a variable thats uncalled.
An animation manager is
where you choose the transition conditions between the animations clips you created.
Animations clips are just multiple sprites separated by a time interval.
To tell the animation manager when to use different animation clips, you
drag a line between 2 animations (called a transition)
This makes it possible for one animation clip to transition to another one.
Create parameters (aka variables) for the transition line to listen to, and add conditions to the transition line so if those variables ever meet the conditions, then the transition will occur.
Then to change those parameters from a script, add an animator component to the script and type (based on the type of parameter you chose)
animator. SetFloat(“ParameterName”, 1)
animator. SetBool(“ParameterName”, true)
Note: Turn off “exit time” if you don’t want the animation to always finish completely before switching.
[SerializeField] is used if
you want a private variable to be visible in the inspector
To create a prefab
Create a folder named “Prefabs” inside the Assets folder and drag a game object form the hierarchy into it.
Note: Changing any prefab instances attributes will change it on all other instances of the prefab as well.
Tensors
A scalars is a
quantities that are fully described by a magnitude
A vector is
an object that has both a magnitude and a direction
A to fully describe a vector you need its
coordinate basis that its being applied to
To toggle a game objects visibility, type
gameObject.SetActive(false)
In c# for strings always use
double quotes
To make a delay coroutine type
Create it and then call it
IEnumerator CoroutineName() { yield return new WaitForSeconds(1f); Debug.Log("waited") }
StartCoroutine(CoroutineName())
To get a script from another script, type
GameObject myObject = GameObject.FindGameObjectWithTag(“tag”);
myObject.GetComponent().FunctionName(“left”);
Note: I tried creating a variable for the script itself like below but it was null. Its possible that the class needs to be imported before I can use it as a type for the variable declaration. ScriptName script = canvas.GetComponent();
When accessing a public Enum from a different script in and imported script you get it from the
class rather than the instance ScriptName.EnumName
To make a scroll list of equally spaced objects, you
Add all the list items as children on an object with a Scroll Rect Component and then add a Vertical Layout Group Component to that object too.
To instantiate a prefab and set it as a child of an existing game object in the hierarchy, type
public GameObject myPrefab;
GameObject content;
// Start is called before the first frame update void Start() { content = GameObject.FindGameObjectWithTag("Content"); GameObject go = Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity); go.transform.SetParent(content.transform); }
.gitignore can be stored
in any subfolder
Package manager sheet
To open package manager, go to
window -> package manager
Before package manager, installation was done by
adding a list item to manifest.json
You can also add a package to the manifest.json by
typing in com.unity.localization under “Add package from git URL” in package manager
To use localization
Basically how localization works is
you create a table with a key per row, and then key value pairs for each language name and translated value.
Create a new folder inside assets folder (can be called Localization for simplicity)
In Edit -> Project Settings -> Localization click create and save the file in the localization folder
To add localization to a text object
Add a Localize String Event Component
Create a table
Add a table reference
Choose the right key for table collection
Create an Update String Function
Drag the text component onto the None and the choose text in the dropdown
https://www.youtube.com/watch?v=lku7f4KNFEo
The best way to ID a component for referencing in code is
idk, tag?