- Home /
Access one function in multiple classes
I'm using a FSM for my AI, with each state being its own class, as in:
public class PatrolState: FSMState
{
public PatrolState()
{
stateID = StateID.Patrol;
}
public override void Reason(GameObject player, GameObject npc)
{
//Check all transition conditions
}
public override void Act(GameObject player, GameObject npc)
{
//Walk patrol route
}
}
Now I notice that I'm using the exact same logic in each state's Act section: a) find the nearest object with some tag, b) pathfinding to that object, c) run a function on that object.
Obviously it would much cleaner (and easier to debug) if I were to encapsulate this logic in a single function that I call in each Act(), but since each state is its own class, it can't see functions that I declare elsewhere. Is there any easy, computationally efficient way to stick this logic in a single place and call it from each Act state?
Answer by Taschenschieber · Jul 04, 2014 at 09:33 AM
Define your Act method in a class "GenericState" which inherits from FSMState. Then, PatrolState and all the other states you use should inherit from GenericState and use the Act method written in GenericState.
You can give some states different behaviours by simply overriding the Act method in these states.
(I'm not sure I understand exactly what you mean - maybe you are simply searching for static functions?)
Ooh that does the trick nicely, thank you! :)
Answer by Kiwasi · Jul 04, 2014 at 11:19 AM
Inheritance works best for "is a" type relationships. However there is another way that is worth mentioning, that is to encapsulate you methods in a separate class and call them from there. If your method does not need to store any data you can create a static class. Otherwise you can create a class that you call with new. I'm thinking something like this:
public static class HelperMethods {
public bool Act(SomeParamater someParamater){
//Do some cool stuff
}
// Some other methods
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613153213im_/https://answers.unity.com/themes/thub/images/avi.jpg)