Unity Code

By | January 2020

Setting up Git

Installing Git Windows 10

  • Install Git – put in an short-named folder like C:\Y\G
  • Don’t need to install Git Bash or Git GUI. Just install the Git Framework, leave rest as default options
  • Clone a project that’s made in GitHub or GitLab

Clone a Project

  • In GitLab, create a new Project without README to see instructions.
  • cd C:\Y\G\
  • git clone “url-link”
  • git add . OR git add Assets (goes directly into Assets Folder)
  • git commit -m “a comment
  • git push origin master

Command Prompt Window Properties Windows 10

  • Change colour, font, text-size, etc
  • “Start In” default is – %HOMEDRIVE%%HOMEPATH% which starts up in C:\Users\(ComputerName)
  • Change change it to – %HOMEDRIVE%\Y
  • Then select dropdown for the folder “G”
  • This will start up Command Prompt automatically in C:\Y\G when searching “cmd” in the Windows 10 Menu Search
  • Opening Command Prompt via Win+R, “cmd” will open up an unmodified Command Prompt
  • Different cmd shortcuts can have different properties

Always pull before pushing

  • git pull origin master
  • git status
  • git add Assets
  • git commit -a -m “a comment
  • git push origin master

Move an object – Transform and Rigidbodies

YouTube – Press Start – Unity Movement [Rigidbody vs Translate]
Using Transform is basically “Rigidbody.Is_Kinematic = true;“.
Translate is better used in moving specific objects that doesn’t require physics.

When using Rigidbodies, call in FixedUpdate instead of Update:
– “FixedUpdate” runs every physics step.
– “Update” runs once per frame, which is good for detecting player input.


YouTube – Jason Weimann – Unity 101: 5 ways to move Unity3D Objects
Using Transform to push against a collider causes the object to “vibrate”.

// Transform SetPosition - Setting the object's position to a new position.
void Update()
{
   transform.position += transform.forward * Time.deltaTime;
}

// Transform Translate - Instead of giving the object a new position, give an amount to move.
void Update()
{
   transform.Translate(Vector3.forward * Time.deltaTime);
}

Rigidbody.Is_Kinematic = true;” means that the object doesn’t interact with the physics sytem, pass through colliders but can move by adding Force.

// Rigidbody AddForce - Adding force every single frame (e.g. acceleration).
Rigidbody RB;
float Force;

void FixedUpdate()
{
   RB.AddForce(transform.forward * Force * Time.deltaTime);
}

// Rigidbody MovePosition - Similar to Transform.translate. Detects physics and collisions.
// Set Rigidbody.Collision_Detection from "Discrete" to "Continuous".
Rigidbody RB;
float Force;

void FixedUpdate()
{
   Vector3 NewPosition = transform.position + (transform.forward * Time.deltaTime);
   RB.MovePosition(NewPosition);
}

// Rigidbody SetVelocity - Set a velocity value (e.g. shooting an object) in Awake method.
// Move the object at a constant rate over time.
Rigidbody RB;
float Force;

void Awake()
{
   RB = GetComponent<Rigidbody>();
   RB.velocity = transform.forward * Force * Time.deltaTime;
}
// Debug.Log(RB.velocity.magnitude);
// Returns the xyz Vector3 coordinate values to a single READONLY float.

Move an object – AddForce Modes

UnityDocs – AddForce and ForceMode

Rigidbody RB;
float xForce, yForce, zForce;
Vector3 TotalForce;

void Start()
{
   TotalForce = new Vector3(xForce, yForce, zForce);
}

void FixedUpdate()
{
   RB.AddForce(TotalForce, ForceMode.Acceleration);   // Acceleration.
   RB.AddForce(TotalForce, ForceMode.Force);          // Continuously applied force.
   RB.AddForce(TotalForce, ForceMode.Impulse);        // Applies an instant force.
   RB.AddForce(TotalForce, ForceMode.VelocityChange); // Applies an instant velocity change.
}

Better Jump

YouTube – Board To Bits – Better Jumping in Unity with 4 Lines of Code

Rigidbody RB;
float FallMultiplier = 2.5f;
float LowJumpMultiplier = 2f;

void Awake()
{
   RB = GetComponent<Rigidbody2D>();
}

void Update()
{
   if (RB.velocity.y < 0) 
   { 
      RB.velocity += Vector2.up * Physics2D.gravity.y * (FallMultiplier - 1) * Time.deltaTime; 
   }
   else if (RB.velocity.y > 0 && !Input.GetButton("Jump"))
   {
      RB.velocity += Vector2.up * Physics2D.gravity.y * (LowJumpMultiplier - 1) * Time.deltaTime;
   }
}

Direction Left or Right Only

int Direction;

void Start()
{  // Direction can be left(1) or right(-1) only.
   Direction = Random.Range(0, 2) * 2 - 1;
}

KeyCode

UnityDocs – KeyCode

void Update()
{
   if (Input.GetKey(KeyCode.Space))
   {
      Debug.Log("Space key was pressed.");
   }
}

Instantiate

UnityDocs – Instantiate

public GameObject Prefab;

void Start()
{
   Instantiate(Prefab, new Vector3(0, 0, 0), Quaternion.identity);
}

Altering a GameObject’s Transform.Rotation

Stack Overflow – Spawning objects with Random Rotation

public GameObject Prefab;

void Start()
{
   Instantiate(Prefab, new Vector3(0, 0, 0), Quaternion.Euler(0.0f, 0.0f, Random.Range(0.0f, 360.0f)));
}

Creating Custom Classes

YouTube – Brackeys – Introduction to Audio
// Reference to a video using custom classes.

public class NewScript : MonoBehaviour {

   [System.Serializable]
   public class CustomClass()
   {
      public string Name;
      public int Value;
   }

   public CustomClass[] NewArray = new CustomClass[2];
   // An array called "New Array" with a size of 2 will show up in the Unity Inspector.

   void Start() {...}
   void Update() {...}
}

Inheritance

YouTube – N3K EN – Inheritance

// New script called "ParentScript".
public class ParentScript : MonoBehaviour {

   protected string Name = SomeName;
   protected int Value = 1;

   // Abstract is a different method signature explained further at 17:05.
   //protected abstract void Awake();
   
   protected virtual void Start()
   {
      Debug.Log("ParentScript " + Value);
   }
}

// "ChildScript" inheriting from ParentScript and its variables.
public class ChildScript : ParentScript {

   protected int NewValue = 2;

   protected override Start()
   {
      base.Start();
      Debug.Log(Name + " " + (Value + NewValue));
   }
}

// A GameObject with ParentScript attached and another GameObject with ChildScript attached.
Unity's Debug.Log will show:
   ParentScript 1
   ParentScript 1
   SomeName 3

// If base.Start(); is removed from ChildScript's Start()...
Unity's Debug.Log will show:
   ParentScript 1
   SomeName 3

// Like a tree diagram - there can be an unlimited number of children for one ParentScript.
// Children can inherit children, each with their own new defined variables.

Scriptable Objects

YouTube- Dapper Dino – Scriptable Objects
Scriptable Objects are template data containers.
e.g. “Character” has the variables name, age or job.
This template can be used to create multiple characters with those variables.
Best used for data that doesn’t change.

[CreateAssetMenu(fileName = "fileName", menuName = "Good/New Character")]
// "Good/" puts "New Character" into a new submenu.

public class Character : ScriptableObject {

   [SerializeField] string Name;
   [SerializeField] int Age;
   [SerializeField] enum Job { None, Mage, Warrior, Assassin }
   [SerializeField] Job ClassType;/* = Job.None;*/

  // Getters makes it READONLY when called elsewhere.
  // Can only change in the Unity Inspector.
  // Written the shorthand way. Normally...
  //public string _Name { get { return Name; } }
  public string _Name => Name;
  public int _Age => Age;
}

Leave a Reply