Reputation: 329
I want to get a JSON from a server but this error appears in the console:
You are trying to create a
MonoBehaviour
using the'new'
keyword. This is not allowed.MonoBehaviour
s can only be added usingAddComponent()
. Alternatively, your script can inherit fromScriptableObject
or no base class at all
UnityEngine.MonoBehaviour:.ctor()
The JSON is like a list of names, for example
[“leaderboard01”, “leaderboard02”, …]
This is my code:
public class BC_PlayerInfo : MonoBehaviour
{
public string LeaderboardId = "";
public BC_PlayerInfo(JsonData jsonData)
{
LeaderboardId = SafeGet(jsonData, "leaderboardId");
}
private string SafeGet(JsonData jsonData, string key)
{
var returnValue = "";
try
{
returnValue = jsonData[key].ToString();
}
catch (Exception e)
{
}
return returnValue;
}
}
And...
private void GetLeaderboadsList()
{
WebClient webClient = new WebClient();
string result = webClient.DownloadString("https://xxxxxxxxx.com/wp-json/vendor/v1/carambolaEventsNames");
Debug.Log("Usuario creado en la WEB: " + result);
List<string> leaderboardIds = new List<string>();
lblist.Clear();
var leaderboardsList = JsonMapper.ToObject(result);
foreach (JsonData leaderboardId in leaderboardsList) lblist.Add(new BC_PlayerInfo(leaderboardId));
foreach (var leaderboardId in lblist)
{
string _leaderboardId = leaderboardId.LeaderboardId;
Debug.Log("LeaderboardName: " + _leaderboardId);
}
}
What am I doing wrong?
Upvotes: 0
Views: 47
Reputation: 580
You can't instantiate objects that inherit from MonoBehavior, by using this line:
lblist.Add(new BC_PlayerInfo(leaderboardId));
you are creating a new instance of a Monobehavior, which is not allowed by Unity. See this post for more details: https://answers.unity.com/questions/653904/you-are-trying-to-create-a-monobehaviour-using-the-2.html
As for your solution, does this class really need to inherit from monobehavior? I would just remove that inheritance or create a separate class that does not inherit from monobehavior.
Upvotes: 3