14-Player Damaging and Lives — Script Communication using “GetComponent”

In the previous update, when the enemy collide with the player, we had the enemy destroy itself, but nothing happened to the player yet. Here, let’s take life off the player when it get hit by an enemy. Here is the flow of thoughts to make it happen:

  • The player needs to have lives, which will be subtracted each time it gets hit
    // define life variable
    // define a PUBLIC Damage method that subtracts the life
    * the Damage is made public so that it can be accessed by the Enemy script when collision with player happens
  • When all the lives are taken, the player will be dead (player game object gets destroyed)
    // if life < 1
    // Destroy player

The biggest challenge here is to have the Enemy script talk to the Player script, that it, call the Damage method in player. To have access to the Player script, we need to get a reference of it using the GetComponent method in Unity.

It should be noted that we can not directly access the <Player> component (i.e., other.GetComponent<Player>()) will not work. Instead, we need to go to the root (other.transform) first, that is, other.transform.GetComponent<Player>(). This is because the only component we can directly access is the “transform” component, and every gameobject has a “transform” component.

Whenever we get the component, it is a good practice to do a null check to make sure that component is accessed successfully before taking an action.

Now, when the player gets hit by the enemy three times, its life will drop to zero and disappear from the scene.

--

--

--

Progress of developing the classic galaxy shooting game using Unity and C#

Recommended from Medium

Dr. Thorpe joins MITH Cash as Chief Architecture Advisor

Gotcha: pyenv-win shims messing with global packages

Azure Functions reCAPTCHA Integration

Why You Need to Be Writing Pseudocode

iBeacons And Hue Lights Tutorial Part 4: Typhoon Dependency Injection Framework

10 Things I Learned as a Coding Bootcamp Grad

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
YShu

YShu

Technologist and Unity developer

More from Medium

A new class of design and arts graduates and more–Herberger Institute highlights from December 2021

How to migrate from LaunchDarkly to ConfigCat

cc-question-mark

Needed: Financing Policies That are Both Affordable AND Sustainable

NFT Archaeology and the Digital Art Revolution with Adam McBride