Simple FSM, assigned to a static enemy cube, changing states/colors. No error but not working.

Hi, I’m just trying to create a simple FSM, which is assigned to a static enemy cube. I was hoping the cube would change states/colors when the player approached.

The code is giving off no errors, but it isn’t working.

If anyone can see the problem and please show me the error that would be great.

  using UnityEngine;
using System.Collections;

public class FSM_Test : MonoBehaviour {
    public Transform player;
    public float playerDistance;
    GameObject enemy;
 


    // Use this for initialization


    public enum State
    {
        Red,
        Blue,
        Green
    }

    private State _state;

    void Start()
    {
      
        _state = State.Red;
    }
    // Update is called once per frame
    void Update()
    {
        playerDistance = Vector3.Distance(player.position, transform.position);


        if (playerDistance < 35f)
        {
            switch (_state)
            {
                case State.Blue:
                    Blue();
                    break;


            }
            if (playerDistance < 25f)
            {
                switch (_state)
                {
                    case State.Green:
                        Green();
                        break;


                }
            }
        }
    }
        private void Red() {

    gameObject.GetComponent<Renderer>().material.color = Color.red;

    }
  private void Blue(){
      
        gameObject.GetComponent<Renderer>().material.color = Color.blue;
      
    }
    private void Green(){
      
        gameObject.GetComponent<Renderer>().material.color = Color.green;
   
    }
}

I think you have the wrong end of the stick with switch statements.

In your player distance if statements set the state like you do in the start function.

Then have one switch statement that has all the states in it, rather than switch statements with one state in them in different places.

1 Like

Thanks for your help. I do believe it’s working! Such a simple thing, but what a rush.