Search Unity

Unity Player authentication and Request with JSON

Discussion in 'Scripting' started by camouflaged_penguin, Oct 26, 2021.

  1. camouflaged_penguin

    camouflaged_penguin

    Joined:
    Jun 1, 2021
    Posts:
    22
    Hi there. When the player starts a game he should authenticate and after that a simple request to a server should be made via JSON. (the authentification should be local for now)

    I am not sure where to put this request and how a simple JSON Server Request could look like.
    Basically i want to retrieve an information which then changes some Materials in the scene.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
  3. camouflaged_penguin

    camouflaged_penguin

    Joined:
    Jun 1, 2021
    Posts:
    22
    It is running correctly with postman but i am stuck when i want to do the same steps in unity to connect to the server and get the data.

    What i want to do:
    1. The Player presses a Button
    2. The Whole Magic which i did manually in/with Postman is done in unity instead.

    i know that i have to use Json for that matter but i never worked with JSON so i don'T have a clue what is needed in Unity to do that stuff.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    JSON is just a data serialization mechanism... work through some tutorials for the basic concept of turning objects into strings (serialization) and the reverse (deserialization).

    Problems with Unity "tiny lite" built-in JSON:

    In general I highly suggest staying away from Unity's JSON "tiny lite" package. It's really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.

    Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window -> Package Manager).

    https://forum.unity.com/threads/jso...-not-working-as-expected.722783/#post-4824743

    https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

    Also, always be sure to leverage sites like:

    https://jsonlint.com
    https://json2csharp.com
    https://csharp2json.io

    PS: for folks howling about how NewtonSoft JSON .NET will "add too much size" to your game, JSON .NET is like 307k in size, and it has the important advantage that it actually works the way you expect a JSON serializer to work in the year 2021.
     
  5. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
    Depending on your server setup & code. Use UnityWebRequest.Post to send data to your server. An example is in the documentation.

    For deserializing json, use newtonsoft json. Either from the asset store (some are quite outdated) or by using the package manager add by package name and fill in
    com.unity.nuget.newtonsoft-json