Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Building a Hierarchical State Machine in Unity: Troubleshooting Virtual Functions

Автор: vlogize

Загружено: 2025-10-11

Просмотров: 0

Описание:

Discover how to effectively create a `hierarchical state machine` in Unity and solve common issues with virtual functions using this comprehensive guide.
---
This video is based on the question https://stackoverflow.com/q/68720042/ asked by the user 'Caleb' ( https://stackoverflow.com/u/16628588/ ) and on the answer https://stackoverflow.com/a/68721400/ provided by the user 'SpicyCatGames' ( https://stackoverflow.com/u/5710382/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Building a hierarchical state machine in Unity, having trouble with virtual functions

Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
Building a Hierarchical State Machine in Unity: Troubleshooting Virtual Functions

When developing a game in Unity, implementing a state machine for player characters can make managing various states easier and more intuitive. However, when working with hierarchical state machines, you may run into issues, especially concerning the inheritance of virtual functions. If you've found yourself puzzled by why certain methods are not being called as expected, you’re not alone. In this post, we'll look at a specific case where the expected output from a state machine does not match reality, and we'll go through the steps needed to resolve the issue.

Understanding the Problem

In our scenario, we're working with a state machine consisting of a PlayerScript and multiple PlayerStates. We expect the system to print a specific sequence of debug logs when updating the player state, but instead, we're only seeing a part of the output. Here's the intended output after one frame of execution:

Entered Stopped State

Blip

Blop

Blorp

Instead, the actual output is:

Entered Stopped State

Blorp

The crux of the issue lies in how we are defining our methods in the LowPriorityState.

Analyzing the Code

Let's take a step back and examine how the state machine is set up. Here’s the relevant code:

Player Script

[[See Video to Reveal this Text or Code Snippet]]

Player States

Base State Class: PlayerState

[[See Video to Reveal this Text or Code Snippet]]

Derived State Class: LowPriorityState

[[See Video to Reveal this Text or Code Snippet]]

Most Derived Class: StoppedState

[[See Video to Reveal this Text or Code Snippet]]

What's Going Wrong?

The crux of the issue is in the way we defined the Update method in the LowPriorityState class:

[[See Video to Reveal this Text or Code Snippet]]

Using the new keyword here creates a new method that hides the base class method instead of overriding it. Thus, when we invoke State.Update(this), it is still calling the overridden method in the base class PlayerState, which is why we are only seeing "Blorp" after the state entry message.

The Solution

To fix this issue, we need to change the new keyword to override, which ensures that we’re truly overriding the base class method rather than hiding it. Here’s the corrected version in the LowPriorityState:

Corrected LowPriorityState Class

[[See Video to Reveal this Text or Code Snippet]]

Conclusion

By making this change, your hierarchical state machine in Unity will route calls to the correct overridden methods, allowing you to see the expected sequence of debug output. It’s essential to be mindful of the differences between method overriding and method hiding in C# , as this can significantly impact how your code behaves. With this fix, your state machine should work seamlessly, providing an effective way to manage different states for your game characters. Happy coding!

Building a Hierarchical State Machine in Unity: Troubleshooting Virtual Functions

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Самый короткий тест на интеллект Задача Массачусетского профессора

Самый короткий тест на интеллект Задача Массачусетского профессора

ТОБОЙ МАНИПУЛИРУЮТ ЕСЛИ… ФРАЗЫ КОТОРЫЕ ИСПОЛЬЗУЮТ ВСЕ МАНИПУЛЯТОРЫ

ТОБОЙ МАНИПУЛИРУЮТ ЕСЛИ… ФРАЗЫ КОТОРЫЕ ИСПОЛЬЗУЮТ ВСЕ МАНИПУЛЯТОРЫ

Typst: Современная замена Word и LaTeX, которую ждали 40 лет

Typst: Современная замена Word и LaTeX, которую ждали 40 лет

Windows 11 26H1 - Microsoft снова переобулись?

Windows 11 26H1 - Microsoft снова переобулись?

MS-DOS Laplink — последовательная передача данных RS232

MS-DOS Laplink — последовательная передача данных RS232

Microsoft begs for mercy

Microsoft begs for mercy

НАЧАЛО ГОДА СУЛИТ НОВЫЕ ПРОБЛЕМЫ YOUTUBE, GOOGLE и отключения ИНТЕРНЕТА. Разбираем важное

НАЧАЛО ГОДА СУЛИТ НОВЫЕ ПРОБЛЕМЫ YOUTUBE, GOOGLE и отключения ИНТЕРНЕТА. Разбираем важное

Why the Radius Is NOT 21 – Quarter Circle Geometry Puzzle

Why the Radius Is NOT 21 – Quarter Circle Geometry Puzzle

Understanding the Discrete Fourier Transform and the FFT

Understanding the Discrete Fourier Transform and the FFT

Как сжимаются изображения? [46 МБ ↘↘ 4,07 МБ] JPEG в деталях

Как сжимаются изображения? [46 МБ ↘↘ 4,07 МБ] JPEG в деталях

AI → 3D → Print

AI → 3D → Print

Vibrant Yellow, Purple & Blue Aura with No Sound 🔇 1 Hour Gradient Screensaver for Aesthetic Vibes

Vibrant Yellow, Purple & Blue Aura with No Sound 🔇 1 Hour Gradient Screensaver for Aesthetic Vibes

Самая быстрая передача файлов МЕЖДУ ВСЕМИ ТИПАМИ УСТРОЙСТВ 🚀

Самая быстрая передача файлов МЕЖДУ ВСЕМИ ТИПАМИ УСТРОЙСТВ 🚀

Твоя ПЕРВАЯ НЕЙРОСЕТЬ на Python с нуля! | За 10 минут :3

Твоя ПЕРВАЯ НЕЙРОСЕТЬ на Python с нуля! | За 10 минут :3

Почему эллипс это сложно и не существует формулы периметра эллипса

Почему эллипс это сложно и не существует формулы периметра эллипса

ПОСТУПАЕМ НА МАТФАК! Вопрос на собеседовании!

ПОСТУПАЕМ НА МАТФАК! Вопрос на собеседовании!

Fun Algebra Challenge

Fun Algebra Challenge

Brain rot in software development...

Brain rot in software development...

Курс Python с Абсолютного нуля! [12 часов из 80] Python курс - качественный старт для начинающих!

Курс Python с Абсолютного нуля! [12 часов из 80] Python курс - качественный старт для начинающих!

Лямбда-выражения в Java — простое полное руководство

Лямбда-выражения в Java — простое полное руководство

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: infodtube@gmail.com