Wednesday, August 21, 2013

UNITY: General Unity Notes

This will be an on-going post with all the little small tidbits I've found while working with Unity.

UPDATE: Each section of the manual will now be broken into sub-categories, starting with " Creating Gameplay "

2013.SEP.11:

Robust C# language feature to prevent clashes between scripts. " Enemy.Controller1 "

Scripts in a later phase can utilize variables and functions in an earlier phase, but not vice versa.  Compile order:
  • Phase 1: Standard Assets, Pro Standard Assets, Plugins
  • Phase 2: Standard Assets/Editor, Pro Standard Assets/Editor, Plugins/Editor
  • Phase 3: All other scripts not inside a folder called Editor
  • Phase 4: All remaining scripts (example: ones inside the Editor folder)
Anything inside a folder called WebPlayerTemplates will not be compiled.

Event Functions:
Update events, Initialization events, GUI events, Physics events:
Awake(), Start(), Update(), FixedUpdate(), LateUpdate(), OnGUI(), etc.

"Transform.Find" Function:
This can be useful when an object has a child that can be added or removed during gameplay. A weapon that can be picked up and put down is one example.

Direct Component Access:
If a public variable of a "Component Type" is declared, you can drag any GameObject that has the component attached to it. This will access the component directly, rather than the GameObject itself.

Unity uses industry standard "Substance" shaders.  Procedural shaders take a much smaller storage footprint than a bitmap image.

Unity Built-In Shaders Guide
Extensive guide regarding Unity's built-in shader models.

Alpha Maps Guide
Guide to creating Alpha maps in photoshop.

Detail Meshes:
Use for any static terrain decorations that are not Trees or Grass.

Grass:
Same as Trees, but doesn't require a mesh.  Just need a texture.

Create:
  • Create > GameObject > Create Other > Wind Zone 
Use Unity's built in TREE BUILDER utility.  
  • add Branch Group
  • tweak
  • add Leaf Group
  • tweak
  • import "Tree Creator" asset package
  • add Materials
    • Nature > Tree Creator Bark
    • Nature > Tree Creator Leaves
  • select Nodes in NodeTree
    • apply Bark shader
    • apply Trees shader

Textures:
Use the "RGBS" format: Store "Specular" information in the Alpha channel, and save with TIFF.  Doesn't work with PNGs.

In order to paint normal map "Splat maps", you have to make sure the Terrain has a normal-map-capable shader applied to it.

If you have 2 or more Terrain textures applied, you can begin to 'Blend' them together using a method similar to Photoshop layer masks.

Using Camera Depth, a variety of effects can be done. One example would be to have Depth 0 render the environment, then Depth 2 render the player's UI and the FPS weapon. That way the UI and weapon is always drawn on top, regardless of penetration etc between gun object and environment.

Prefabs:
Prefabs and Assets are different.  Assets have certain limitations that Prefabs do not when working in the project.

You can assign an icon to an object by clicking on the icon next to the name in the Inspector, then selecting one of the default icons, or a custom icon of choice.  Name of object will be displayed as well.

Object Labels:
Items in the Project view can be labeled by clicking the little blue "..." in the object's preview.  Custom labels can be created by just typing in a name.

Component View:
There are two main types of Properties: Values and References.

2013.SEP.03:

Unity Effects!

Easily put a trail on bullets this way.


2013.SEP.0C.D: Unity Beginner Scripting (Unity Official)

" Classes "
Use classes to to store and organize your information, and how to create constructors to work with your class.

Analogy:

  • Classes : Factory
  • Functions : Machines
  • Variables : Boxes
Example scripts: (basic movement, inventory, and shooting):

Name of classes should be the same as the script.  Avoid changing it unless absolutely necessary.  A class is a container for variables and functions, an organizational tool for "object oriented programming".  The idea is to split the script into multiple scripts, each handling one task.

A PlayerControl script that has all "movement", "inventory", and "shooting" all in the same script should be spit into individual scripts.  Each script handling a task makes it easier to read and more efficient to write.

Sub-Classes can be created within the script/class, and can be instantiated within the same script. 

Example:

//declare sub-class
public class Stuff
{
    public int bullets;
    public int grenades;
    public int rockets;
}
//creating an Instance (an object) of the "Stuff" class
public Stuff myStuff = new Stuff();

Data type: name of the class,  Name: "myStuff",  new,  end with name of class again.  Using " () " at the end means that a "constructor" is being used.

A " Constructor " is a function that can give default values to the variables in your class.

Example 01:
// Constructor, this goes inside sub-class
public Stuff ()
{
    bullets = 1;
    grenades = 1;
    rockets = 1;
}

Example 02:
// Constructor example 2, using parameters
public Stuff (int bul, int gre, int roc)
{
     bullets = bul;
     grenades = gre;
     rockets = roc;
}

Then instantiate using:
" public Stuff myStuff = new Stuff(50,5,5); "
This will instantiate a "new" instance of "Stuff", a "Stuff" type variable, with 50 bullets, 5 grenades, and 5 rockets.

Notes about Constructors:
  • name of the Constructor is always the name of the Class
  • Constructors never have a return type, not even "void"
  • a Class can have multiple different Constructors, but only one is called when an object is initialized
  • different instances of the Constructor will be used depending on their parameters

" Instantiate " 

Create clones of Prefabs during run time.

One example is firing a Rocket from a bazooka.  Each Rocket would have to be instantiated into the game world so that it could be fired.

Example:
(inside instantiate script class)
public Rigidbody rocketPrefab;
public Transform barrelEnd;

void Update()
{
   if(Input.GetButtonDown ("Fire1"))
   {
      Instantiate(rocketPrefab);
   }
}

Drag and drop Prefab item into the public field.  Unfortunately, this setup will only instantiate the object at origin (0,0,0).  Instead, create an empty GameObject and position it at the barrel.  Drag this object into the Transform variable field "barrelEnd".  Then use:

" Instantiate (Prefab to clone, Position, Rotation to use); ", which would be:

" Instantiate ( rocketPrefab, barrelEnd.position, barrelEnd.rotation ); "

Rocket should be created at barrel tip, but falls down. To remedy this, define a new "Rigidbody" types variable called "rocketInstance", then define rocket instance:

Rigidbody rocketInstance;
rocketInstance = Instantiate(rocketPrefab, barrleEnd.position, barrelEnd.rotation) as Rigidbody;

At this point, you can use anything in the Rigidbody class, such as:

Rigidbody.AddForce (Transform.forward * amount);
or
" rocketInstance.Addforce (barrelEnd.forward * 5000); "

All is well, except that these objects need to be destroyed or else they'll eat up memory.  Create a new script that destroys the object over time.

script:
public class RocketDestruction : MonoBehavior
{
   void Start ()
   {
      Destroy (gameObject, 1.5f);
   }
}


2013.SEP.02.C: Unity Beginner Scripting (Unity Official)

" Delta Time "
Can be used in games to smooth and interpret values.  "Delta" means difference, and Time.DeltaTime is the time between each Update() or FixedUpdate().  Can be used to smooth out movement inputs, or other values.  It changes movement values to "per second" rather than "per frame".

Use: Multiply variable by " Time.DeltaTime "



" GetComponent "
Use this function to address properties of other scripts or components.

A script in Unity is considered a custom component.  "GetComponent" is used to modify other scripts on the same GameObject, or even other objects.  The function is very expensive, and should only be called on the "Awake()" function or "Start()" function.

Use:
" GetComponent(); "
" otherGameObject.GetComponent(); " (after declaring a proper variable)


" OnMouseDown "
Can detect clicks on Colliders or GUI Text elements.

Use:
void OnMouseDown()
{
    (Do something) ;
}

example things that can go between the curlies:

  • rigidbody.AddForce( transform.forward * 500 );
  • rigidbody.useGravity = true; 

2013.SEP.02.B: Unity Beginner Scripting (Unity Official)

" Destroy "
  • Use:
    • " Destroy(GameObject/Component, optional delay); "
  • by default, this destroys the current game object, along with its attached script, but a public GameObject variable "other" can be created, so another object can be referenced within Unity.
  • "GetComponent" function
    • Use: " Destroy (GetComponent(); "
  • a timed delay can be employed as the optional 2nd argument
    • Use: " Destroy(gameObject, 3f); " (floats only)
" GetButton and GetKey "

Part of Unity's "Input" Class.  Buttons return a Boolean.
  • when nothing is pressed:
    • GetButtonDown: FALSE
    • GetButton: FALSE
    • GetButtonUp: FALSE
  • when button is pressed:
    • GetButtonDown: TRUE
    • GetButton: TRUE
    • GetButtonUp: FALSE
  • when button is released:
    • GetButtonDown: FALSE
    • GetButton: FALSE
    • GetButtonUp: TRUE
It's recommended to use "GetButton" over "GetKey" because players can configure them before game launches.  You can configure buttons via "Input Manager" under the Edit menu.

Examples:
  • GetButton Syntax: " bool var = Input.GetButton("string"); "
  • GetKey Syntax: " bool var = Input.GetKey(Keycode.key); "

" GetAxis "

Unlike GetButton and GetKey, "GetAxis" returns a float value between -1 and 1.  Axis are setup in the Input Manager under the Edit menu.  Also unlike a button which only is a positive button value, GetAxis also needs a negative button value.  Other settings required for setting up an Axis:
  • Gravity:
    • speed of return to zero. Higher values snap, lower values float.
  • Sensitivity:
    • opposite of Gravity, speed of getting to 1 or -1. Higher value the more responsive, lower the value the more smooth.
  • Dead:
    • if using a joystick, controls the deadzone.
  • Snap:
    • returns to zero if both positive and negative buttons are held (for buttons)
To use: 
  • " float h = Input.GetAxis("Horizontal"); "
  • " float v = Input.GetAxis("Vertical"); "
" Input.GetAxisRaw "
Only returns whole values, useful for 2D that requires precise controls rather than smooth values (JWX NOTE: For menu navigations, etc).

2013.SEP.02:

" Translate and Rotate "
  • transform.Translate(new Vector3(0,0,1));
    • takes new vector3
    • inside the Update();, it'll be updated by every frame
    • multiplying by "Time.DeltaTime" will convert this from a frame by frame operation to a X-per-frame operation.
    • can use shortcuts, Vector3.forward, Vector3.up, etc.
    • multiply "moveSpeed" variable 
    • only use when RigidBody "Is Kinematic"
" Look At "
  • can be used to point and object's FORWARD vector to another object's transform location
  • " transform.LookAt(target); "
  • add public Transform type variable called "target"
  • drag gameObject from Hierarchy into the "target" field in Unity UI
" Lerping "

Vector3.Lerp:
  • used to smooth a transition between two Vector3 values
  • short for "Linear Interpolate"
  • use: " Vector3.Lerp(from Vector3. to Vector3. time float) "
    • Lerp(from, to, time);
      • Lerp(transform.position, newPosition, Time.DeltaTime);
        • can multiply Time.DeltaTime with a float
Mathf.Lerp:
  • used to smooth out two float values
  • use " Mathf.Lerp(from float, to float, time float) "
  • encapsulate in function that runs every frame (Update(), etc)
Color.Lerp:
  • used for Lerping color values
  • use " Color.Lerp(from Color, to Color, time float) "
  • encapsulate in function that runs every frame (Update(), etc)
Use "void Awake () " function for defining new Lerp Variables.

2013.AUG.30:

  • "object.enabled = true" to enable objects
  • "object.enabled = false" to disable objects
  • "object.enabled = !object.enabled" to toggle
    • "!" exclamations are used to denote "not"
  • "gameObject.SetActive(true)" 
  • " Debug.Log("Active Self: " + myObject.activeSelf); "
    • returns a boolean of whether or not the object itself is active
  • " Debug.Log("Active Hierarchy: " + myObject.activeHierarchy); "
    • returns a boolean of whether or not the object Hierarchy is active
  • void Update ();
    • frame rate dependent, and frame rate fluctuates depending on load
    • for things like controllers
  • void FixedUpdate ();
    • refresh is fixed, update is consistent
    • used for things requiring physics
  • void LateUpdate();
    • follow cameras, procedural animations, gathering last known states

2013.AUG.29:

  • .ToString();
    • method used to cast a result to a string.

2013.AUG.20:

  • Negative Z-Axis is "Forward"
  • Use Mathf.Ceil to set a ceiling and cast to integer displays
  • Use Mathf.Lerp and Mathf.LerpAngle for smoothing operations

No comments: