Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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 /
  • Help Room /
avatar image
0
Question by T3CHN0B4BBL3 · Mar 03, 2020 at 11:50 PM · state machinedesign-patterns

Trying to understand the State Pattern - having trouble implementing

Hi all,

Sorry ahead of time for the formatting, I can't for the life of me get the spacing to work. Anyways, I'm self taught and looking to understand the State pattern by implementing it into the enemy AI in my project. I've been following the guides on Game Design Patterns and Ray Wenderlich.

Here are the classes that I have so far:

 public class StateMachine : MonoBehaviour
 {
     [SerializeField] State currentState;
 
     public StateMachine(State startingState)
     {
         currentState = startingState;
     }
 
     // Update is called once per frame
     void Update()
     {
         currentState.Tick();
     }
 
     
 
     public void ChangeState(State newState)
     {
         currentState = newState;
     }
 }


 public abstract class State : MonoBehaviour
 {
     public abstract void Tick();
 }

 public class PatrolState : State
 {
     float patrollingSpeed = 1.5f;
 
     float minWorldSpaceX = -8;
     float minWorldSpaceY = -4;
     float maxWorldSpaceX = 8;
     float maxWorldSpaceY = 4;
 
     bool destinationReached;
 
     Vector3 patrolDestination;
     
     public override void Tick()
     {
         //Patrolling 
         if (destinationReached == true)
         {
             //Choose new destination
             float xDestination = Random.Range(minWorldSpaceX, maxWorldSpaceX + 1);
             float yDestination = Random.Range(minWorldSpaceY, maxWorldSpaceY + 1);
 
             patrolDestination = new Vector3(xDestination, yDestination, 0);
 
             transform.LookAt(patrolDestination);
 
             Debug.Log("Enemy patrolling to " + patrolDestination);
 
             destinationReached = false;
 
         }
 
         else if (destinationReached == false)
         {
             transform.position = Vector3.MoveTowards(transform.position, patrolDestination, Time.deltaTime * patrollingSpeed);
 
             if (transform.position == patrolDestination)
             {
                 Debug.Log("Destination reached.");
                 destinationReached = true;
             }
         }
     }
 }

 public class ChaseState : State
 {
     GameObject player;
     float speed = 3;
 
     public ChaseState(GameObject chaseObject)
     {
         player = chaseObject;
     }
 
     private void Start()
     {
         
     }
 
     public override void Tick()
     {
         transform.LookAt(player.transform);
         transform.Translate(transform.forward * speed * Time.deltaTime, Space.World);
     }
 }

 public class EnemyAI : MonoBehaviour, IDestructable 
 {
     [SerializeField] float speed;
     [SerializeField] float patrollingSpeed;
 
     public GameObject player;
 
     public int Health { get; set; }
     public int MaxHealth { get; set; }
 
     StateMachine stateMachine;
     PatrolState patrolState;
     ChaseState chaseState;
 
     // Start is called before the first frame update
     void Start()
     {
         Health = 10;
         MaxHealth = 5;
 
         
         patrolState = new PatrolState();
         chaseState = new ChaseState(player);
         stateMachine = new StateMachine(patrolState);
     }
 
     // Update is called once per frame
     void Update()
     {
         Collider2D detection = Physics2D.OverlapCircle(transform.position, 3);
 
         if (detection != null)
         {
             if (detection.GetComponent<IPlayer>() != null)
             {
                 Debug.Log("Player detected");
                 stateMachine.ChangeState(chaseState);
 
             }
         }
     }
 
     public void TakeDamage(int damage)
     {
         Health -= damage;
         Debug.Log("I've been hit!");
 
         if (Health <= 0)
         {
             Kill();
         }
     }
 
     public void Kill()
     {
         Destroy(gameObject);
     }
 
     private void OnDrawGizmos()
     {
         Gizmos.DrawWireSphere(transform.position, 3.0f);
     }
 }

I've attached the State Machine class to my Enemy prefab, but I'm getting an error saying NullReferenceException: Object reference not set to an instance of an object StateMachine.Update () (at Assets/Scripts/States/StateMachine.cs:17), which leads me to believe that nothing is being passed in when the State Machine is being created.

Like I said, I'm self taught so it's probably something simple, I just can't seem to figure out what's wrong.

Comment
Add comment
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

0 Replies

· Add your reply
  • Sort: 

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.

Follow this Question

Answers Answers and Comments

200 People are following this question.

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

Related Questions

NullReferenceException while following Unity3d College tutorial @JasonWeimann 0 Answers

Notification area for Civ type game 1 Answer

Having a issue with a NullReferenceException 1 Answer

Best practice for 'cleanly' sharing properties among multiple behaviour scripts? 0 Answers

Twiching Velocity using RigidBody.addForce. 0 Answers


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