Classes

Classes

Classes define a type of object. Each object of a class has a reference which makes it unique. An example for a class is “Animal”. An class can have subclasses which we call inheritors. For the case of “Animal” we could have a sub-class “Penguin”, “Pig”, etc… objects can be created from a class for example you could make a Penguin object call it “Dyp” and another Penguin object and called it “Sloom”.

As mentioned before MonoBehaviours is a class and by default when creating a script in Unity it will have a template that automatically makes the script inherit MonoBehaviours. You do not have to derive from MonoBehaviours, if you wish you can derive from other classes, or from nothing.

Example of a class:

/// <summary>
/// script used to rotate a character.
/// </summary>
public class CharacterRotator
{
    protected readonly Character m_Character;

    /// <summary>
    /// Constructor.
    /// </summary>
    /// <param name="character">The character.</param>
    public CharacterRotator(Character character)
    {
        m_Character = character;
    }
    
    /// <summary>
    /// Rotate the character in respect to the camera.
    /// </summary>
    public virtual void Tick()
    {
        var charVelocity = m_Character.IsDead
            ? Vector2.zero
            : new Vector2( m_Character.CharacterInput.Horizontal, m_Character.CharacterInput.Vertical);
        
        if (Mathf.Abs(charVelocity.x) < 0.1f &&
            Mathf.Abs(charVelocity.y) < 0.1f) {
            return;
        }
        float targetRotation = 
            Mathf.Atan2(charVelocity.x, charVelocity.y) 
            * Mathf.Rad2Deg + m_Character.CharacterCamera.transform.eulerAngles.y;
        
        Quaternion lookAt = Quaternion.Slerp(m_Character.transform.rotation,
            Quaternion.Euler(0,targetRotation,0),
            0.5f);

        m_Character.transform.rotation = lookAt;
    }
}