Reputation: 4786
I am creating a chess game, in my code I am generating objects to represent the pieces.
These are all of type Pawn
, Rook
, King
etc and are derived from the Piece
class.
However, when I attempt to create a new Pawn
as such:
return new Pawn(location, gameObj);
Despite the values of location
and gameObj
being valid, the returned value is null.
The (unfinished) Piece
and Pawn
classes are defined as such:
public class Piece : MonoBehaviour
{
protected Coord location;
protected bool isWhite;
protected bool specialUsed = false;
void displayMarkers(List<Coord> targets)
{
}
public void moveTo()
{
}
public void resetColour()
{
}
public virtual void displayTargets()
{
}
}
and:
public class Pawn : Piece
{
public Pawn(Coord loc, GameObject gameObj)
{
location = loc;
if (loc.y < 4) { isWhite = true; } else { isWhite = false; }
}
public override void displayTargets()
{
}
}
Any help would be greatly appreciated as this has me completely stumped. Thanks!
Upvotes: 2
Views: 541
Reputation: 16662
You are using Unity,
In Unity you cannot instantiate a MonoBehaviour
using new Pawn()
, you must do that through AddComponent<T>
method.
As a result, parameterized constructors are useless.
Example:
var pawn = gameObject.AddComponent<Pawn();
pawn.isWhite = true;
See the documentation for more information:
http://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html
Upvotes: 1