SceneLinkedSMB

Checked with version: 2017.3

-

Difficulty: Beginner

SceneLinkedSMB is a class that extends how StateMachineBehaviours work. It allows for Behaviour on states in the Animator state machine to keep a reference to the MonoBehaviour. Although SceneLinkedSMBs can be used wherever you need to reference a specific MonoBehaviour, they were designed with the idea of separating logic and functionality. An animator controller contains a state machine which is ideal for controlling flow of execution. Using SceneLinkedSMBs you can make calls to public functions on a MonoBehaviour allowing it to control functionality because it can more easily obtain scene references. In this way, SceneLinkedSMBs can control logic as part of a state machine and the MonoBehaviours they are linked to control functionality.

Usage of SceneLinkedSMB

To code a new Behaviour using the SceneLinkedSMB, you need to:

  • Make your new class inherit SceneLinkedSMB. As the class is a Generic, you need to specify the type of the MonoBehaviour that it should hold. For example: public class EnemyAttackState: SceneLinkedSMB

  • Initialize on every GameObject with an animator using that state. In the above example, we could add the following line to the Start() function of Enemy class: SceneLinkedSMB.Initialise(animator, this); In this example, animator is a reference to the animator with a state which has a SceneLinkedSMB on. Note that you only need to call this once, even if you have 10 differents scripts on multiples states. As long as they all inherit from SceneLinkedSMB they will all get initialized.

  • Override any state functions you need. More functions are added to SceneLinkedSMB to allow for more specific control of when functionality happens. In your class you can access a protected member called m_MonoBehaviour that has the same type as the class’s generic type parameter. So continuing our example, m_MonoBehaviour would be of type Enemy.

Example

Enemy.cs

Code snippet

public class Enemy: MonoBehaviour
{
    Animator animator;

    void Start()
   {
        animator = GetComponent<Animator>();
        SceneLinkedSMB<Enemy>.Initialise(animator, this);
    }

    public void TrickerAttack()
   {
    // ...
    }
}

EnemyAttackState.cs

Code snippet

public class EnemyAttackState: SceneLinkedSMB<Enemy>
{
    public override void OnSLStateEnter (Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        // m_MonoBehaviour is of type Enemy 
        m_MonoBehaviour.TrickerAttack ();
    }
}

Related tutorials