In building a GOAP system, I have a parent Action
class that hold most of the logic used for planning, while children classes inherit from it to provide a small amount of their own functionality, such as EatFoodAction
.
During planning, I need to create a shallow copy of an Action
to act as a node in my action graph, and I cannot for the life of me figure out how to write a Copy()
function that can return a new instance of the child class, and not simply a new instance of the parent Action
class.
It's not the copying fields that I can't do, it's the returning of a class of the right type.
This answer still requires overriding the copy function in each child class, something that I'd like to avoid.
A simple function to copy fields can only return the parent type, and I don't particularly want to create an override function for each child. A shallow copy will do just fine:
public class Action
{
public Action Copy()
{
var newAction = new Action();
// copy fields
return newAction;
}
}
The cloned action then gets passed into an ActionNode(Action action)
class:
// planning code
var newNode = new ActionNode(oldAction.Copy())
I've tried generics, but they still need the exact type of the child class to work, and I'm not too sure how to use reflection without needing to the exact type to cast it to anyway.
How can I go about either returning the child class type, or is there some way to simply copy a class without needing to manually specify the exact type? Everything still inherits from the base Action
class, so surely there is a way?
Thank you :)
Aucun commentaire:
Enregistrer un commentaire