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

Objects getting data from other objects.

Discussion in 'Scripting' started by Dire_Lemming, Oct 28, 2020.

  1. Dire_Lemming

    Dire_Lemming

    Joined:
    Oct 20, 2020
    Posts:
    2
    I'm making a game where I need one object, a type of worker, to get a value from their corresponding objects, the buildings they can work. Currently I'm assigning both a string and running through a list checking it like so:

    Code (CSharp):
    1.         int capacity = 0;
    2.         foreach (Building building in Global.activeBuildings)
    3.         {
    4.             if (this.Type == building.Type)
    5.             {
    6.                 capacity += building.currentCapacity;
    7.             }
    8.         }
    However this would definitely not scale well as I add more buildings. My initial thought was a list of lists (e.g. a list of farms in a list of buildings lists) but I don't know how to tell the object the correct list to check. Is there some way to do this or a better structure I could use?
     
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    Yes you have some options, but that depends on your actual needs.

    Can you already tell that some object should only refer to some other objects?
    Do you have a situation where an instance of the same type of object has different objects to refer to?

    If Yes then No, use dictionaries based on types.
    If Yes then Yes, use dictionaries based on instances.

    To be in control of such system, pay special attention to how you create your objects, and redefine GetHashCode and Equals methods. Learn more about it, unless you want to shoot yourself in the foot.

    Here is a useful link (after you've read the official API and guidelines)
    https://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/

    (Your payloads may be lists.)
     
    Dire_Lemming likes this.
  3. Dire_Lemming

    Dire_Lemming

    Joined:
    Oct 20, 2020
    Posts:
    2
    Thanks, looks like I've got some reading to do.