• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by Harry Buck · Feb 08, 2012 at 02:02 PM · keypressswitch-casefsm

Changing between states in state machine with a keypress

Hey I have made a state mac$$anonymous$$ne that is suppose to switch states with the press of the space key and prints w$$anonymous$$ch state it is in on the log file. It works as intended, but I was wondering if there was an easier way to do it, or if my way is good or bad with regards to memory consumption and other optimization practices. Also if anybody can show me how I would handle the key press in other file (such as a Main.cs file) then that would be great too. Thanks.

Just attach the C# code to anyt$$anonymous$$ng and it should work.

using UnityEngine; using System.Collections;

public class abctest1 : MonoBehaviour {

 public enum State{
     Active, 
     Inactive,
     Dead, 
     Complete,

}

public int stateCounter=0;

public State behaviorState;

 IEnumerator Start () {
     //behaviorState = abctest1.State.Active;
     behaviorState = State.Active;
     
     w$$anonymous$$le(true){
         switch(behaviorState){
         case State.Active:
             ActiveState();
             break;
         case State.Inactive    :
             InactiveState();
             break;
         case State.Dead    :
             DeadState();
             break;
         case State.Complete    :
             CompleteState();
             break;
         }
         yield return 0;
     }
 }
 
 public void ActiveState(){
     Debug.Log("Active State");
     if(stateCounter == 1)
     behaviorState = State.Inactive;
     
 }
 
 public void InactiveState(){
     Debug.Log("Inactive State");
     if(stateCounter == 2)
     behaviorState = State.Dead;
 }
 
 public void DeadState(){
     Debug.Log("Dead State");
     if(stateCounter == 3)
     behaviorState = State.Complete;
 }
 
 public void CompleteState(){
     Debug.Log("Complete State");
     if(stateCounter == 4)
     behaviorState = State.Active;
 }
 
 public void Update () {
     if(Input.GetKeyDown("space"))
     stateCounter = stateCounter + 1;
     print(stateCounter);
     if(stateCounter == 5)
     stateCounter = 6 - stateCounter;
 
 }

}

Comment

People who like this

0 Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jessy · Feb 08, 2012 at 04:26 PM 0
Share

Why is Update public?

3 Replies

· Add your reply
  • Sort: 
avatar image

Answer by Berenger · Feb 08, 2012 at 03:23 PM

Well, that's the idea. What is going to change know is the nature of the event changing the state. From a space stroke to anyt$$anonymous$$ng, life to low or player to far etc.

Another to do without the loop on the switch is, at least I t$$anonymous$$nk it's a good solution but I'm not that advanced so be carefull :p, to use object-oriented design. Each behavior is an implementation of an interface, and you can create an object of that implementation according to the event (if( state == death ) behavior = new Death(), etc).

Other advice, a good way to control performance is to not update the AI every frame. Not$$anonymous$$ng more simple in your case because everyt$$anonymous$$ng is here already : replace yield return 0 by yield return WaitForSeconds( frequency );

Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image

Answer by Harry Buck · Feb 08, 2012 at 07:09 PM

@Berenger So with the new implementation of the interface, are you saying that I should make a new "Death" class and have the functionality for the Death in that class. If you could provide an example that would be great, I am more of a visual learner.

@Jessy I made it public because later on I want to be able to access t$$anonymous$$s state mac$$anonymous$$ne in another file. I out the key press in the same class just for simplicity. Later on I would like to have it where the key press functionality is in another file but still gets the state mac$$anonymous$$ne from the file that the FSM is in.

Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image

Answer by Jessy · Feb 08, 2012 at 05:31 PM

I don't know anyt$$anonymous$$ng about state mac$$anonymous$$nes. T$$anonymous$$s is what came to mind.

 #pragma warning disable 0649
 
 using System;
 using UnityEngine;
 
 public class abctest1 : MonoBehaviour {
 
 [Serializable] class State {
     public Action action;
     public State nextState;
     public string announcement;
 } [HideInInspector][SerializeField] State state;
 [SerializeField] State active, inactive, dead, complete;
 
 void Awake() {
     // These next two blocks can't be serialized by the Editor.
     active.nextState = inactive;
     inactive.nextState = dead;
     dead.nextState = complete;
     complete.nextState = active;
         
     // Put real stuff in the braces.
     active.action = () => {};
     inactive.action = () => {};
     dead.action = () => {};
     complete.action = () => {};
         
     // T$$anonymous$$s should be done in the Editor but dealing with Reset()
     // is a pain and not directly relevant to the question.
     state = active;
         
     Debug.Log(active.announcement);
 }
 
 void Update() {
     if(Input.GetKeyDown("space")) {
         state = state.nextState;
         Debug.Log(state.announcement);
     }
     state.action();
 }
 
 }
Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Key Press Queuing 2 Answers

How do I rotate an object at a constant rate a specific angle on key down? 3 Answers

How to create a collider-trigger that will start an animation when you press E 0 Answers

Multiple keypresses at once aren't regitered? 1 Answer

Implementing collision and key pressing at once 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges