- Home /
The question is answered, right answer was accepted
Problems with a custom struct ("does not contain a constructor that takes x arguments")
I have created a custom struct that definitely has 3 and only 3 arguments, but when I try to declare variables of that custom type, Unity tells me that my custom struct "does not contain a constructor that takes `3' arguments."
Here are the details. I am creating an in-game user feedback system that uses, among other things, a text console that will (hopefully) work something like the console in the Unity editor. (But for messages relevant to the player like "Fuel tanks expected to last only another 2 minutes at this speed" or "No torpedoes remaining, you must find new torpedoes" etc.)
To help me out, I have created two enums and a custom struct as a container for the sorts of messages that will be sent:
public enum FeedbackLevel {
Normal,
Warning,
Error,
}
public enum FeedbackForm {
AudioOnly,
Speech,
SpeechAndText,
Text,
}
public struct UserFeedback {
public FeedbackForm feedbackForm;
public FeedbackLevel feedbackLevel;
public string feedbackMessage;
}
Then I use a global game event system to transmit UserFeedback messages to a class that's designed to handle them.
Here's my problem. When I am assembling the UserFeedback object, I want to be able to do it straightforwardly, like I would most any Unity struct (e.g., Vector3). So, like this:
UserFeedback uF = new UserFeedback (FeedbackForm.Text, FeedbackLevel.Normal, "Refueling complete!");
But this triggers the error that
the type 'UserFeedback' does not contain a constructor that takes '3' arguments
Now, it does work if I declare the UserFeedback object the long way:
UserFeedback uF;
uF.feedbackForm = FeedbackForm.Text;
uF.feedbackLevel = FeedbackLevel.Normal;
uF.feedbackMessage = "Refueling complete!";
This works just fine. But it's clunky. Why won't C# allow me to construct it on one line with the "new" keyword, like I would a Vector3 or any other struct?
Thanks in advance.
Answer by Cherno · Apr 19, 2016 at 06:31 AM
You have to define the constructor.
public struct UserFeedback {
public FeedbackForm feedbackForm;
public FeedbackLevel feedbackLevel;
public string feedbackMessage;
public UserFeedback(FeedbackForm ff, FeedbackLevel fl, string fm) {
feedbackForm = ff;
feedbackLevel = fl;
feedbackMessage = fm;
}
}
Follow this Question
Related Questions
What are the properties of a good key hash? 1 Answer
C# Point structure 1 Answer
Enum instead of numbers in arrays 1 Answer
Change variable in inspector depending on enum using struct 0 Answers
How to save ComputeBuffer? 0 Answers