Search Unity

bunch of codes and Event handlers to implement simple client/server scenario

Discussion in 'Scripting' started by mahdiii, Mar 15, 2019.

  1. mahdiii

    mahdiii

    Joined:
    Oct 30, 2014
    Posts:
    799
    It is my scenario.
    I display player's weapon as a list. First, I send a request to get the weapon list from a server and then show it as a list.
    Every weapon has a name, image, price, etc.
    Players can sell their weapons by clicking on it. When a player clicks on a weapon item, a request is sent and after receiving its response, it is removed from the weapon list.

    You can see for this really simple scenario, there are bunch of codes to handle events(back and forth), sending requests and receiving responses.
    How can I simplify it? Is there any better approach to handle it?
    For example using data binding?

    Another question is about services. How can I send fake request data and receive fake responses?
    For example, I wrote "new PlayerWeaponsService().GetWeapons()" to send a request(getWeapon). How can I utilize interfaces? Do I need something like DI/IOC or ServiceLocator?

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4.  
    5. public class BaseElementEventArgs : EventArgs
    6. {
    7.     public int Id;
    8. }
    9.  
    10. public class WeaponItemView : MonoBehaviour
    11. {
    12.     [SerializeField] private Text _titleText;
    13.     [SerializeField] private Text _costText;
    14.     [SerializeField] private Button _sellButton;
    15.  
    16.     public event EventHandler<BaseElementEventArgs> SellButtonPressedEventHandler;
    17.     private int _id;
    18.  
    19.     public void Initialize(Weapon weapon)
    20.     {
    21.         _sellButton.onClick.AddListener(() =>
    22.         {
    23.             SellButtonPressedEventHandler?.Invoke(this,new BaseElementEventArgs {Id = _id});
    24.         });
    25.         _id = weapon.Id;
    26.         _titleText.text = weapon.Name;
    27.         _costText.text = $"Price: {weapon.Cost}";
    28.     }
    29.  
    30.     public void TrySell(int id)
    31.     {
    32.         if (id==_id)
    33.         {
    34.             Destroy(gameObject);
    35.         }
    36.     }
    37. }
    38.  
    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Threading.Tasks;
    5. using UnityEngine.Events;
    6.  
    7. [Serializable]
    8. public class Weapon
    9. {
    10.     public int Id;
    11.     public string Name;
    12.     public int Cost;
    13. }
    14. //---------------------------------------------------------------------------------------
    15.  
    16. public class WeaponItemListView : MonoBehaviour
    17. {
    18.     [SerializeField] private GameObject _weaponItemPrefab;
    19.     [SerializeField] private Transform _rootTransform;
    20.     [SerializeField] private IntUnityEvent SellWeaponButtonPressedEvent;
    21.  
    22.     private readonly List<GameObject> _weaponObj = new List<GameObject>();
    23.  
    24.     public void Initialize(IEnumerable<Weapon> weapons)
    25.     {
    26.         _weaponObj.ForEach(Destroy);
    27.         _weaponObj.Clear();
    28.         foreach (var weapon in weapons)
    29.         {
    30.             var weaponObj = Instantiate(_weaponItemPrefab, _rootTransform);
    31.             _weaponObj.Add(weaponObj);
    32.             weaponObj.GetComponent<WeaponItemView>().SellButtonPressedEventHandler += OnSellButtonPressed;
    33.             weaponObj.GetComponent<WeaponItemView>().Initialize(weapon);
    34.         }
    35.     }
    36.  
    37.     public void SelectedWeaponWasSold(int id)
    38.     {
    39.         foreach (var obj in _weaponObj)
    40.         {
    41.             if (obj)
    42.             {
    43.                 obj.GetComponent<WeaponItemView>().TrySell(id);
    44.             }
    45.         }
    46.        
    47.     }
    48.  
    49.     private void OnSellButtonPressed(object sender, BaseElementEventArgs e)
    50.     {
    51.         SellWeaponButtonPressedEvent.Invoke(e.Id);
    52.     }
    53. }
    54. //---------------------------------------------------------------------------------------
    55. [Serializable]
    56. public class WeaponListUnityEvent : UnityEvent<List<Weapon>>
    57. {
    58. }
    59. //---------------------------------------------------------------------------------------
    60. [System.Serializable]
    61. public class GetWeaponListResponseMessage : BaseResponseMessage
    62. {
    63.     public IEnumerable<Weapon> Weapons;
    64. }
    65.  
    66. [System.Serializable]
    67. public class BaseResponseMessage
    68. {
    69.     public int StatusCode;
    70.     public bool SuccessStatus;
    71.     public string Message;
    72. }
    73. //---------------------------------------------------------------------------------------
    74. public class PlayerWeaponsService
    75. {
    76.     public async Task<GetWeaponListResponseMessage> GetWeapons()
    77.     {
    78.         //var content=new StringContent("");
    79.         //var response = await new HttpClient()
    80.         //    .PostAsync(ServiceUrlStrings.GetWeaponList,content);
    81.         //if (!response.IsSuccessStatusCode) return null;
    82.         //var json = await response.Content.ReadAsStringAsync();
    83.         //return JsonUtility.FromJson<GetWeaponListResponseMessage>(json);
    84.         return new GetWeaponListResponseMessage
    85.         {
    86.             SuccessStatus = true,
    87.             Weapons = new List<Weapon>
    88.             {
    89.                 new Weapon {Id = 0, Cost = 100, Name = "Shotgun"},
    90.                 new Weapon {Id = 1, Cost = 100, Name = "AK47"},
    91.                 new Weapon {Id = 2, Cost = 100, Name = "G3"}
    92.             }
    93.         };
    94.     }
    95.  
    96.     public async System.Threading.Tasks.Task<BaseResponseMessage> SellWeapon(int id)
    97.     {
    98.         //HttpContent content = new StringContent(id.ToString());
    99.  
    100.         //var response = await new HttpClient().PostAsync(RequestUrlStrings.SellWeapon, content);
    101.         //if (!response.IsSuccessStatusCode)
    102.         //    return null;
    103.  
    104.         //var json = await response.Content.ReadAsStringAsync();
    105.         //return JsonUtility.FromJson<BaseResponseMessage>(json);
    106.         return new BaseResponseMessage {SuccessStatus = true};
    107.     }
    108. }
    109.  
    110. public class ServiceUrlStrings
    111. {
    112.     public static readonly string GetWeaponList = "";
    113. }
    Bussiness logic--> Send requests and receive responses and handle events

    Code (CSharp):
    1. using System.Collections.Generic;
    2. using System.Linq;
    3. using UnityEngine;
    4.  
    5. public class WeaponListViewModel : MonoBehaviour
    6. {
    7.     [SerializeField] private WeaponListUnityEvent WeaponListChangedEvent;
    8.     [SerializeField] private IntUnityEvent WeaponWasSoldEvent;
    9.  
    10.     private List<Weapon> _weaponList = new List<Weapon>();
    11.  
    12.     public List<Weapon> WeaponList
    13.     {
    14.         get { return _weaponList; }
    15.         set
    16.         {
    17.             if (_weaponList == value)
    18.                 return;
    19.  
    20.             _weaponList = value;
    21.             WeaponListChangedEvent.Invoke(_weaponList);
    22.         }
    23.     }
    24.  
    25.     public async void OnSellWeaponButtonPressed(int id)
    26.     {
    27.         var response = await new PlayerWeaponsService().SellWeapon(id);
    28.         if (response != null && response.SuccessStatus)
    29.         {
    30.             WeaponWasSoldEvent.Invoke(id);
    31.         }
    32.     }
    33.  
    34.     private async void OnEnable()
    35.     {
    36.         var response = await new PlayerWeaponsService().GetWeapons();
    37.         if (response != null && response.SuccessStatus)
    38.         {
    39.             WeaponList = response.Weapons.ToList();
    40.         }
    41.     }
    42. }
     
    Last edited: Mar 15, 2019