I am learning how to post data to a web server from Unity3d as a first step towards creating a leaderboard for my game. Right now I have a very simple script in Unity that posts a name and score to my server. The PostScoreURL maps to a create action in Rails (when sent as a POST). It is very simple but works on a basic level.
Unity has a WWW class that I am using to POST to the server. This class has an error property but it is always coming up as 500 Internal Server Error; it has this error if the user is successfully created or if the user is not created due to a validation problem. I would like to add to my Rails app so that I can send more meaningful error messages back to Unity so that the user will know what is going on. For example, if they try to create a user that already exists, they should be notified that they need to use a different name.
Here is my code:
The Unity script:
string PostScoreURL = "http://localhost:3000/users";
string name = "Melanie";
int score = 8732;
WWW www;
bool requestSent = false;
void OnGUI()
{
if (GUI.Button(new Rect(0, 0, 100, 100),"Post Score"))
{
WWWForm form = new WWWForm();
form.AddField("user[name]", name);
form.AddField("user[score]", score);
www = new WWW(PostScoreURL,form);
requestSent = true;
}
if(requestSent && www.isDone)
{
print (www.error);
requestSent = false;
}
}
From the Rails app:
user.rb:
class User < ActiveRecord::Base
attr_accessible :name, :score
validates_presence_of :name, :score
validates_uniqueness_of :name
end
Here is my create action:
def create
@user = User.new(params[:user])
@user.save
end
I would like to send back relevant error messages to Unity. For example: Missing Username, Missing Score, Username taken.
You shouldn’t consider your business rule errors as connection errors, that is, those errors should be treated in the server side, returning to the client a “successful” response with an internal error code, defined by you.
I don’t know RoR, it probably let you define error codes in the response, but in my case (that don’t use RoR) we created a response class with error codes that is serialized and returned to the client. After that, WWW class calls a parser that will verify the error codes. Also, WWW watches for connection errors on http://WWW.error.