Component
How to use Components to add behaviour/functionality to GameObjects in Unity!
Components attach to GameObjects to give them functionality/behaviour.
A component is an Instance of a Class that exists in the Scene.
Custom components can be created to build any functionality you require in your game.
Examples
Create a custom component
Custom components are created by coding a Class, and then making it inherit from MonoBehaviour. This allows you to click-drag it onto any GameObject or Prefab, and gives the class access to MonoBehaviours’ features.
Getting a component on the current GameObject
…
Building a physics object from scratch
Rigidbody is a Unity Component that allows the physics engine to take control of your GameObject.
Sphere Collider is a Unity Component that allows your GameObject to bump into things, so it won’t fall through the floor.
By adding both these components to a GameObject, it will create a realistic ball that will roll with physics.
Building a dog
Components allow you to build objects from modular pieces, so, to make a dog, you wouldn’t necessarily have a Component named “Dog”.
Instead, we build it out of Components that add behaviour, and attach them to the GameObject that represents the dog.
Bark is a custom Component that contains a Bark()
function.
Jump is a custom Component that contains a Jump()
function.
Microchip is a custom Component that contains microchip data about the dog’s owners.
Building a Player character
CharacterController is a Unity Component that contains a useful Move()
function which allows us to collide with objects while moving.
Player is a custom Component that simply ‘tags’ a GameObject as the player. It’s used instead of Unity’s tag system.
MoveHorizontal is a custom Component that stores Input values and puts them into the CharacterController’s Move()
function.
CharacterInfo lets us give our player a name, etc. It can also attach to any other character that needs a name.
Notes
- Public member variables will be initialized automatically by the editor.
public List<int> myList;
will work.public List<int> myList = new List<int>()
is still recommended.