Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Player Interaction With Objects | Player Behavior
Fighting Game in Unity
course content

Course Content

Fighting Game in Unity

Fighting Game in Unity

1. Unity Animation System
2. Player Behavior
3. Enemy Behavior
4. Improve the Game
5. Improve the Flappy Bird Game

Player Interaction With Objects

Interfaces

An interface is like a contract that defines a set of methods and properties that a class must implement. It allows you to specify what functionality a class should have without providing the implementation details.

Example

Let's say you're making a game in Unity, and you want to create different types of weapons like swords, guns, and bows. You could create an interface called IWeapon that outlines the basic actions any weapon should be able to perform, such as Attack() and Reload().

Now, any class that wants to be considered a weapon in your game must implement this interface. For instance, you could have a Sword class or a Gun class.

By using interfaces, you can ensure that all your weapons have the same basic functionality (Attack() and Reload()), but each can have its own unique implementation. This makes your code more modular and easier to manage, especially as your game grows in complexity.

This is the interface that we used in our game for marking the enemies as objects that could get attacked.

TryGetComponent

Key Points

  • raycastHit: This refers to the result of a raycast hit. When you cast a ray in Unity, you get information about what object;
  • .TryGetComponent(out IGetAttacked getAttacked): This method attempts to retrieve a specific component from the GameObject's transform. The out keyword is used to assign the retrieved component to the variable getAttacked, if successful. If not, it will ignore anything under that if;
  • IGetAttacked: This is the interface type that the code is trying to retrieve from the GameObject. It specifies that the GameObject must have a component that implements the IGetAttacked interface.

If the GameObject hit by the raycast has a component that implements the IGetAttacked interface, the getAttacked variable will hold a reference to that component after this line executes. Otherwise, getAttacked will be assigned a value of null.

What is the purpose of the TryGetComponent method in Unity?

Select the correct answer

Everything was clear?

Section 2. Chapter 5
We're sorry to hear that something went wrong. What happened?
some-alt