Hi,
I use a database, mongoDB and i have followed a tutorial how to setup etc.
But he doesn’t tell how to go further, like displaying it and save it to the cloud. Does someone know this?
Thanks Sam
This is my script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Linq;
public class networker : MonoBehaviour {
private string apiKey = "API";
private string mlabUrl = "Link";
public Score[] scores;
[System.Serializable]
public class Score {
public int score;
public string name, date, deviceID;
}
public IEnumerator UpdateHighScore(int newHighScore) {
string request = mlabUrl
+ "?&q={\"deviceID\":\"" + SystemInfo.deviceUniqueIdentifier + "\"}"
+ "&m=true&u=true&apiKey=" + apiKey;
Score scoreData = new Score();
scoreData.score = newHighScore;
scoreData.name = PlayerPrefs.GetString("playerName", "defaultname");
scoreData.date = System.DateTime.Now.ToString();
scoreData.deviceID = SystemInfo.deviceUniqueIdentifier;
string json = JsonUtility.ToJson(scoreData);
json = "{ \"$set\" : " + json + "}";
var scoreBytes = System.Text.Encoding.UTF8.GetBytes(json);
UnityWebRequest www = UnityWebRequest.Put(request, scoreBytes);
www.SetRequestHeader ("content-type", "application/json");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
} else {
Debug.Log("New high score set to " + newHighScore.ToString());
}
}
[System.Serializable]
private class Wrapper<T>
{
public T[] array;
}
public IEnumerator GetScores() {
UnityWebRequest www = UnityWebRequest.Get(mlabUrl + "?&apiKey=" + apiKey);
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
}
else {
string json = "{ \"array\": " + www.downloadHandler.text + "}";
Wrapper<Score> wrapper = JsonUtility.FromJson<Wrapper<Score>> (json);
scores = wrapper.array.OrderByDescending(go => go.score).ToArray();
}
}
public static networker instance;
void Awake() {
if (instance == null)
instance = this;
}
}