- Home /
Constructors always returning void
This issue seems like it's really simple, but am completely failing to get it to work.
I have a basic data class AI order which has one constructor and one overridden method.
class AIOrder
{
var name:String;
// Constructor
function AIOrder()
{
name = "GenericOrder";
}
// Overriden
function ExecuteOrder(brain:ShipAIBehavior)
{
}
}
I extend the class to represent other order types, overriding the Execute function (I have 10 different types here, this is the simples).
class AttackNearestOrder extends AIOrder
{
function AttackNearestOrder()
{
name = "AttackNearest";
}
function ExecuteOrder(brain:ShipAIBehavior)
{
brain.OrderWaitForTarget();
}
}
It seems like it should be simple enough. I usually access this by something like this...
var order:AttackNearestOrder = new AttackNearestOrder();
aiCraft.AddOrderToOrderList(order );
However, the constructor always returns void. If I try `new AIOrder()` an object of type AIOrder is correctly returned by the constructor, just fails when I try to get the extended class.
The funny thing is that this worked when AIOrder and its extended versions where a subclass of another class (that inherited from MonoBehavior). I moved them out as I needed to be able to construct AIOrders from other classes, and now the trouble has started.
Ideas? Feel like it must be very simple.
Well I'll guarantee that you're constructor is not returning void. It simply can't. So, my guess is that there is a null reference happening in `AddOrderToOrderList.` Can you post the code for that function please (or whatever calling function that throws the error)?
The error actually occurs in the line before it, it's a "Cannot convert void to AttackNearestOrder" error. So I don't think it has anything to do with AddOrderToOrderList at the moment.
Answer by Chris42 · Nov 26, 2012 at 08:05 PM
The problem: The constructor `new AttackNearestOrder()` was conflicting with the name of a method in the script! That method of course had a return type of void and was being called first.
Silly of me!
Answer by Loius · Nov 26, 2012 at 07:32 PM
I'm not certain it's -necessary-, but I usually use a super call to invoke the parent contructor explicitly:
function Constructor(params) { super(params); }
Knowing how odd some things can be at times, I'd at least give that a try to see if it helps.
This wasn't exactly the answer, but doing this let me to the correct solution (see my answer below).