- Home /
error with a constructor
Hi i'm trying to make a deck of cards but ran into a problem with my PlayCard constructor :
public class PlayingCard : MonoBehaviour
{
private enum Suits {Diamond,Heart, Club, Spade };
private enum Color {Black, Red};
private int _value;
private Suits _suit;
private Color _color;
private void Start()
{
_suit = Suits.Diamond;
} // there seems to be an error with this constructor, any idea's ?
public PlayingCard(int value, Suits suit, Color color)
{
_value = value;
_suit = suit;
_color = color;
}
}
Can't see anything wrong with it. Seems fine to me.
Answer by WarmedxMints · Mar 04, 2019 at 12:45 AM
You can't have a constructor on a monobehavior. You can't use the new keyword to create one anyway, that's what addcomponent is for. To do what you want there, just make a void that does it. For example, if you had this in your PlayingCard Class;
public void Init(int value, Suits suit, Color color)
{
_value = value;
_suit = suit;
_color = color;
}
When you add the playingcard class to a gameobject you would do;
var go = Instatiate(prefab);
var playingCard = go.AddComponent<PlayingCard>();
playingCard.Init(myIntValue, mySuit, myColour);
While most you said is correct, please don't call "a method" "a void". You don't say i'm driving "a blue". I'm driving a car which might happen to be blue but it's still a car. "void" is just the return type of the method (just like blue is only the color of the car).
I've seen this slaughter of common terms a lot recently. Besides methods without a valid return value (the return type is "void") there are also void pointers. So using "void" as a synonym for methods is not only ambiguous but also misleading and just wrong (just like the color blue should not be used as a synonym for a car). Strangely this missuse seem to only apply to the pseudo type void. Nobody calls a method that returns an integer "an int".
Answer by xxmariofer · Mar 04, 2019 at 12:45 AM
you cant use Constructors with monobehaviour classes, since are classes that must have an object attached to. you need to use the start awake for initializing your monobehaviour objects. if you dont want it to be atached to an object remove the monobehaviour.
Your answer
Follow this Question
Related Questions
Making a List for Inventory System, Got an error in finding constructors and variables 1 Answer
Using an enum in a class constructor. 1 Answer
Why is the value of my enum being reset outside of my class constructor? 0 Answers
Inconsistent Accessibility: Parameter type is less accessible than method 1 Answer