Search Unity

List - storing gameobjects prefabs and accessing int values within for basic sum total

Discussion in 'Scripting' started by dingaling007, Jan 18, 2020.

  1. dingaling007

    dingaling007

    Joined:
    Oct 27, 2016
    Posts:
    26
    I'm trying to get the sum total int value from a List of gameobjects. The gameobjects are all the same prefab and have an int that is a random number that's changing periodically.

    Essentially I'm trying to get a snapshot state of all the gameobjects int value in the list to grab there current random number. Add them together to display on a text UI. Then do it again a second later. I don't want the result to keep adding onto the previous sum total.
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    What did you try? What is your problem?
    You do have a list of gameobjects. You said these gameobjects have a script that contains a (public) integer. You can access this script with GetComponent on the gameobjects reference. You can do that in a for-loop and simply add all the numbers together.
    If that's all you are doing, i would consider directly saving it as a list of the relevant script, instead of gameobject. So you dont need to call GetComponent all the time. If you still need the gameobject as well, calling .gameObject is pretty fast compared to the other way around.
     
  3. dingaling007

    dingaling007

    Joined:
    Oct 27, 2016
    Posts:
    26
    I have a solar panel prefab that has a random number that is the watt output. This is changing its value also at random intervals.

    I want to display the total watts of all the solar prefabs. So at first I tried to add the random int variable to a public list when the prefab is instantiated. Then add them together. But this just keeps adding the numbers up crazy high because I have the listname.Add(randomInt) in the update function on the solar prefabs script, I assume its adding 100's of new list entries.

    If I have gameobjects added to the list just the once in start(), I should be able to access the randomInt in a for loop? What is the syntax to access the prefab int with gameobjects?

    I've tried the following both failures

    Code (CSharp):
    1.       for (int i = 0; i < listname.Count; i++)
    2.             {
    3.              Int_total_watts += listname[i].GetComponent<prefab_script>.randomInt;
    4.             }
    error CS0119: 'GameObject.GetComponent<T>()' is a method, which is not valid in the given context

    and a silly attemt here:

    Code (CSharp):
    1.   Int_total_watts = listname.GetComponent<prefab_script>.randomInt.Sum();
    error CS1061: 'List<GameObject>' does not contain a definition for 'GetComponent' and no accessible extension method 'GetComponent' accepting a first argument of type 'List<GameObject>' could be found (are you missing a using directive or an assembly reference?)


    I mostly understand the errors, but I don't know the correct syntax to access the int variable within the gameobjects stored in the list.
     
    Last edited: Jan 18, 2020
  4. dingaling007

    dingaling007

    Joined:
    Oct 27, 2016
    Posts:
    26
    Maybe I need to rephrase the question: How to keep a running sum total of a list of random numbers that change every second.

    some psuedo code to get an idea.

    //run every 1second, essentially polling what the prefabs random number is

    sum_Total_at_This_Point_In_Time =
    prefab(1).currentRandomIntValue
    +
    prefab(2).currentRandomIntValue
    +
    prefab(3).currentRandomIntValue


    DisplayResult_To_text_UI = sum_Total_at_This_Point_In_Time
     
    Last edited: Jan 19, 2020
  5. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    I'm again not entirely sure what your problem is. Do what you posted in a loop (iterating over all objects and adding their values together) whenever you need to, then display the resulting sum. For convenience wrap all this up in a function and - if you want it to run every for example 1 second - possibly use a Coroutine for execution.

    You seem to know how to get your values from the objects, how to calculate a sum and, based on your comment, how to execute it every 1 second. And i find it hard to believe you dont know about loops.
    So you seem to know everything required to repeatedly update some ui value with your sum.

    Sorry for being useless :confused:
     
  6. dingaling007

    dingaling007

    Joined:
    Oct 27, 2016
    Posts:
    26
    Ok I think this is the best way to explain. See attached simple sample scene. you will see the prefabs showing there random numbers. And look a the total. Its not able to display the correct result - Its accumulating instead of displaying the correct total. And im aware why its happening but cant work out how to fix it- its the way I'm using the list? multiple entries every time its called?
     

    Attached Files:

    Last edited: Jan 19, 2020
  7. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    Wow, i could swear your second post did not exist when i wrote my last reply. On that regard, it's probably better to use the edit function instead of double posting. I'll give a pseudo'ish code example for how it should work.

    Code (CSharp):
    1. // We have access to a list of solar panels (gameobjects)
    2. List<GameObject> solarPanels = ... ; // contains all your solar panels and is up to date
    3.  
    4. // A function that returns the sum of some values in a list of scripts
    5. public float GetWattSum(){
    6.     // First we define our temporary total sum, starting at 0
    7.     float totalWatt = 0f;
    8.  
    9.     // Then we iterate all the gameobjects ...
    10.     for(int i = 0; i < solarPanels.Count; i++){
    11.         // .. and add their values to the sum, like you did in your example
    12.         totalWatt += solarPanels[i].GetComponent<script_name>().randomVal;
    13.     }
    14.     // Lastly we return the sum
    15.     return totalWatt;
    16. }
    17.  
    18.  
    Whenever you call the function 'GetWattSum()' it will return you the sum of all randomVals saved in the scripts script_name of your GameObject list. Ideally you'd parametrize the function, such that it receives the list it works on. I left that out for the example. To improve performance, the List should ideally be of type List<script_name>, such that you dont have to constantly call GetComponent<script_name>().

    By the way (and this may be your whole problem now that i saw your second reply) the error you got which says "GameObject.GetComponent<T>()' is a method, which is not valid in the given context" basically just means that you forgot the paranthesis after GetComponent<>. It has to be GetComponent<someType>(), including the paranthesis.

    I hope with this we are getting a bit closer to fixing your problem. Sorry for missing your second post tho.
    I didnt look at your sample scene yet, as i currently dont have Unity installed on this computer. So tell me if the above helps you, otherwise i will look into it more deeply when i'm back at a computer with Unity installed.
     
  8. dingaling007

    dingaling007

    Joined:
    Oct 27, 2016
    Posts:
    26
    Ah excellent that's working beautifully! and so much better then having the prefab add its float list entry! Accessing the Gameobject and the float value within has solved this for me! much appreciated many thanks for your efforts with this!

    And sorry about the second post, it was stuck for moderator approval for ages, im not sure why.

    Now I just need to work out how to not use getcomponent as you suggested.