Script Communication in Unity using GetComponent

Day 8 — Aspiring Game Creator

2D Game Dev: Galaxy Shooter

Objective: Implement a Lives Systems in Galaxy Shooter.

Accessing variables and methods from one script to another is actually quite easy, but can be confusing too.

Whether the variable or method is on the same game object or a different one, the method to access the script is GetComponent.

If the method is on the same game object, the game object reference is implied so there’s no need to get the game object, whereas if the method is on another game object the reference to the game object MUST BE established first then the reference to the script and finally the method.

To allow one script to access the data or methods on other scripts the variables or methods need to be public.

For this initial implementation of the Lives System, the Player script will maintain the lives data, the enemy will initiate player damage and the player will update the UI.

Pseudo Code:

  • Enemy has a collision
  • Enemy checks the game object tag of the other colliding
  • If the tag is the “Player” and null check passes then
  • Enemy damages Player
  • Enemy explodes
  • Enemy sets its mesh to false
  • Enemy destroys itself
  • Player loses a life
  • Player checks for game over flag
  • Player updates UI lives count
  • If game over flag is true, Player updates UI & Player destroys itself
  • UI updates player lives
  • If game over is true then UI displays Game Over text

Above, the pseudo code breaks down the logic into three segments: Enemy, Player & UI.

ENEMY: detects collision with player.

Enemy collision

Above, the enemy needs to damage the player, the damage method resides on the player script, so first create the reference to the game object. With the OnTriggerEnter method the collider is returned, so using other.transform gives access to the entire game object and using the GetComponent method allows access to the script <Player>.

Next, calling the damage script is like calling any method, using the player game object reference call the damage method:

PLAYER: receives DAMAGE from enemy and communicates with UI.

Player communicating with UI

Below, once the player damage method is called, a life is subtracted and the game over logic is checked.

Finally, below, the UI updates the lives remaining, and if the game over method is called then displays GAME OVER.

Aspiring Game Creator