Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Setting a ton of variables that may or may not be null. Try set?

Discussion in 'Scripting' started by ChrisF12000, Aug 22, 2023.

  1. ChrisF12000

    ChrisF12000

    Joined:
    Aug 20, 2023
    Posts:
    9
    Hello,

    I am parsing data from JSON into gameobjects and sometimes some information is missing. This leads to either the object being skipped or breaking the script. Is there a way to make it so that I can set the non-null variables and set a placeholder for the null ones?

    Code (CSharp):
    1. void InstantiatePlanes(IList<FlightData> flightslist)
    2.     {
    3.         foreach(FlightData flight in flightslist)
    4.         {
    5.             try
    6.             {
    7.                 MeshFilter p = Instantiate(plane);
    8.                 double relativeBearing = GetBearing((double)flight.lat, (double)flight.lng);
    9.                 Variables.Object(p).Set("hex", flight.hex);
    10.                 Variables.Object(p).Set("flag", flight.flag);
    11.                 Variables.Object(p).Set("reg_number", flight.reg_number);
    12.                 Variables.Object(p).Set("lat", flight.lat);
    13.                 Variables.Object(p).Set("lng", flight.lng);
    14.                 Variables.Object(p).Set("alt", flight.alt);
    15.                 Variables.Object(p).Set("dir", flight.dir);
    16.                 Variables.Object(p).Set("speed", flight.speed);
    17.                 Variables.Object(p).Set("status", flight.status);
    18.                 Variables.Object(p).Set("aircraft_icao", flight.aircraft_icao);
    19.                 Variables.Object(p).Set("distance", flight.distance);
    20.                 Variables.Object(p).Set("offset", offset);
    21.                 Variables.Object(p).Set("relativeBearing", relativeBearing);

    partial code snippet

    I'd rather not put a try/catch for every single one of those set methods, but if I need to I will if there isn't a better option.
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    Not sure what the signature of this Set method is, but you could likely encapsulate it in a method that takes a string and a
    Func<T>
    delegate, and have your try/catch in said method.
     
    ChrisF12000 likes this.
  3. ChrisF12000

    ChrisF12000

    Joined:
    Aug 20, 2023
    Posts:
    9
    I'll give it a shot, thanks!
     
    spiney199 likes this.
  4. kdchabuk

    kdchabuk

    Joined:
    Feb 7, 2019
    Posts:
    47
    CodeSmile, ChrisF12000 and spiney199 like this.