Course Content
Fighting Game in Unity
Fighting Game in Unity
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 theGameObject
's transform. Theout
keyword is used to assign the retrieved component to the variablegetAttacked
, if successful. If not, it will ignore anything under thatif
;IGetAttacked
: This is the interface type that the code is trying to retrieve from theGameObject
. It specifies that theGameObject
must have a component that implements theIGetAttacked
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.
Thanks for your feedback!