Search Unity

variables adding up between objects with same script

Discussion in 'Scripting' started by Smokeythebud, Sep 20, 2017.

  1. Smokeythebud

    Smokeythebud

    Joined:
    Aug 9, 2017
    Posts:
    34
    hello all, and thanks in advance. I made a small piece of script for a space game I am working on, the code is to attach to my planet prefabs to hold some info about the planet. The code works great for one object, but when I add more planets they add the new values to the old one rather than just keeping it all separate. Anyway here is my code

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Planet : MonoBehaviour {
    6.  
    7.     public static int resources = 200;
    8.     public int planetWealth;
    9.     public  int planetSize;
    10.  
    11.     void Start ()
    12.     {
    13.  
    14.         int randWealth;
    15.         int randSize;
    16.        
    17.  
    18.         randWealth = Random.Range(1, 3);
    19.         if (randWealth == 1)
    20.         {
    21.             int res = resources;
    22.             planetWealth = res / 4; // randomly decides if new planet is rich, middle, or poor
    23.         }
    24.         else if (randWealth == 2)
    25.         {
    26.             planetWealth = 0;
    27.         }
    28.         else
    29.         {
    30.             int res = resources;
    31.             planetWealth = res / 4;
    32.         }
    33.  
    34.  
    35.  
    36.         randSize = Random.Range(1, 3);
    37.         if (randSize == 1)
    38.         {
    39.             int res = resources;
    40.             planetSize = res / 4;
    41.             resources = res + planetSize + planetWealth;// randomly sets if planet is Large, med, or small
    42.         }
    43.         else if (randSize == 2)
    44.         {
    45.             planetSize = 0 + planetWealth;
    46.         }
    47.         else
    48.         {
    49.             int res = resources;
    50.             planetSize = res / 4;
    51.             resources = res - planetSize + planetWealth;
    52.         }
    53.  
    54.         Debug.Log("Planet Wealth: " + planetWealth);
    55.         Debug.Log("Planet size: " + planetSize);
    56.         Debug.Log("Planet Resources : " + resources);
    57.         Debug.Log("Random Size" + randSize);//checking my values as i code
    58.         Debug.Log("Random Wealth: " + randWealth);
    59.     }
    60.  
    61. }
    62.  
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    static variables are stored at the 'class level'. For any static variable in the class, each instance of the class will access the same 1 variable.
     
    Smokeythebud likes this.
  3. Smokeythebud

    Smokeythebud

    Joined:
    Aug 9, 2017
    Posts:
    34
    ah hah, thanks again its just when I look over my own code so much its easy to miss the small stuff static variables are accessing the actual area of memory correct?
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    not sure what "actual area of memory" means :)

    but I could show a quick example:
    Code (csharp):
    1.  
    2. public class SomeClass {
    3.  int a;
    4.  string b;
    5.  static float f;
    6. }
    7.  
    If I have 20 'SomeClass', each has its own 'a' and 'b' but there is only 1 'f'. :)
     
    Smokeythebud likes this.
  5. DeathQuake

    DeathQuake

    Joined:
    Oct 24, 2012
    Posts:
    64
    Static variables are used when only one copy of the variable is required, so it basically uses only one memory allocation.
     
    Smokeythebud likes this.
  6. Smokeythebud

    Smokeythebud

    Joined:
    Aug 9, 2017
    Posts:
    34
     
  7. Smokeythebud

    Smokeythebud

    Joined:
    Aug 9, 2017
    Posts:
    34
    Thanks again, you all keep me rolling forward
     
  8. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Cool - enjoy yourself :)
     
  9. Smokeythebud

    Smokeythebud

    Joined:
    Aug 9, 2017
    Posts:
    34
    These are my mostly finished classes, I'm going to comment out a piece in the player script because that's the next part it need help with. When my player who has a fleet which can Attack() and Defend() collides with a planet which also has a fleet how can I compare the attack to the defense and then based on those results subtract the correct health. really all I need is the ability to grab the total attack from the planet

    Player Script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Player : MonoBehaviour {
    6.     public Fleet playerFleet;
    7.     int sloop = 20;
    8.     int corsair = 10;
    9.     int frigate = 5;
    10.     int carvahal = 5;
    11.     int warship = 2;
    12.  
    13.     // Use this for initialization
    14.     void Start()
    15.     {
    16.         playerFleet = new Fleet(sloop, corsair, frigate, carvahal, warship);
    17.  
    18.     }
    19.    
    20.     // Update is called once per frame
    21.     void Update ()
    22.     {
    23.        
    24.     }
    25. /*
    26.     void OnTriggerEnter(Collider other)
    27.     {
    28.         if (other.gameObject.CompareTag("EnemyPlanet"))
    29.         {
    30.             if (playerFleet.Attack() > )
    31.             {
    32.  
    33.             }
    34.         }
    35.  
    36.     }
    37. */
    38. }
    39.  
    Planet Script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Planet : MonoBehaviour
    6. {
    7.     public Fleet planetFleet;
    8.     public int resources = 200;
    9.     public int planetWealth;
    10.     public int planetSize;
    11.     int numSloop;
    12.     int numCor;
    13.     int numFrig;
    14.     int numCarv;
    15.     int numWs;
    16.  
    17.     void Start()
    18.     {
    19.         RandomWealth();
    20.         RandomSize();
    21.         resources += planetSize + planetWealth;
    22.         while (resources >= 5)
    23.         {
    24.             RandomFleet();
    25.         }  
    26.         planetFleet = new Fleet(numSloop, numCor, numFrig, numSloop, numWs);
    27.  
    28.        /* Debug.Log("Planet Wealth: " + planetWealth +
    29.                   "\nPlanet size: " + planetSize +
    30.                   "\nPlanet Resources: " + resources);
    31.         Debug.Log("numSloop: " + numSloop +
    32.                   "\nnumCor: " + numCor +
    33.                   "\nnumFrig: " + numFrig +
    34.                   "\nnumCarv: " + numCarv +
    35.                   "\nnumWs: " + numWs);*/
    36.     }
    37.     private void Update()
    38.     {
    39.  
    40.  
    41.     }
    42.     public void RandomWealth()
    43.     {
    44.         int randWealth;
    45.         randWealth = Random.Range(1, 3);
    46.         if (randWealth == 1)
    47.         {
    48.             int res = resources;
    49.             planetWealth = res / 4; // randomly decides if new planet is rich, middle, or poor
    50.         }
    51.         else if (randWealth == 2)
    52.         {
    53.             planetWealth = 0;
    54.         }
    55.         else
    56.         {
    57.             int res = resources;
    58.             planetWealth = res / 4;
    59.         }
    60.     }
    61.  
    62.     public void RandomSize()
    63.     {
    64.         int randSize;
    65.         randSize = Random.Range(1, 3);
    66.         if (randSize == 1)
    67.         {
    68.             int res = resources;
    69.             planetSize = res / 4;
    70.             // randomly sets if planet is Large, med, or small
    71.         }
    72.         else if (randSize == 2)
    73.         {
    74.             planetSize = 0 + planetWealth;
    75.         }
    76.         else
    77.         {
    78.             int res = resources;
    79.             planetSize = res / 4;
    80.         }
    81.     }
    82.  
    83.     public void RandomFleet()
    84.     {
    85.         int randomShip;
    86.         int sloopCost = 5;
    87.         int corCost = 10;
    88.         int frigCost = 10;
    89.         int carCost = 15;
    90.         int wsCost = 20;
    91.  
    92.         randomShip = Random.Range(1, 6);
    93.         if (resources >= sloopCost)
    94.         {
    95.             if (randomShip == 1)
    96.             {
    97.                 if (resources >= sloopCost)
    98.                 {
    99.                     numSloop += 1;
    100.                     resources -= sloopCost;
    101.                 }
    102.             }
    103.             else if (randomShip == 2)
    104.             {
    105.                 if (resources >= corCost)
    106.                 {
    107.                     numCor += 1;
    108.                     resources -= corCost;
    109.                 }
    110.             }
    111.             else if (randomShip == 3)
    112.             {
    113.                 if (resources >= frigCost)
    114.                 {
    115.                     numFrig += 1;
    116.                     resources -= corCost;
    117.                 }
    118.             }
    119.             else if (randomShip == 4)
    120.             {
    121.                 if (resources >= carCost)
    122.                 {
    123.                     numCarv += 1;
    124.                     resources -= corCost;
    125.                 }
    126.             }
    127.             else if (randomShip == 5)
    128.             {
    129.                 if (resources >= wsCost)
    130.                 {
    131.                     numWs += 1;
    132.                     resources -= wsCost;
    133.                 }
    134.             }
    135.         }
    136.     }
    137. }
    138.  
    139.  
    as soon as I finished those nested if else statements I wished I had just made them switches lol

    Fleet class:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [System.Serializable]
    6. public class Fleet
    7. {
    8.     public int numSloop;
    9.     public int numCorsair;
    10.     public int numFrigate;
    11.     public int numCarvahal;
    12.     public int numWarShip;
    13.  
    14.     public Fleet(int s, int cor, int frig, int carv, int ws)
    15.     {
    16.         numSloop = carv;
    17.         numCorsair = cor;
    18.         numFrigate = frig;
    19.         numCarvahal = carv;
    20.         numWarShip = ws;
    21.     }
    22.     // set up Ship objects
    23.  
    24.     public Ship sloop = new Ship(1, 2, 2);
    25.     public Ship corsair = new Ship(5, 2, 2);
    26.     public Ship frigate = new Ship(10, 4, 4);
    27.     public Ship carvahal = new Ship(4, 10, 4);
    28.     public Ship warship = new Ship(15, 10, 15);
    29.  
    30.  
    31.     public int Attack()
    32.     {
    33.         int totalAttack;
    34.         totalAttack = (sloop.attk * numSloop) + // collect attack power * numer of current ships
    35.                       (corsair.attk * numCorsair) + // for each ship type
    36.                       (frigate.attk * numFrigate) +
    37.                       (carvahal.attk * numCarvahal) +
    38.                       (warship.attk * numWarShip);
    39.         totalAttack = Random.Range(0, totalAttack);// sets total defense to a random range to resolve battles and add a randomness to attacks
    40.         return totalAttack;// returns total attack power for fleet
    41.  
    42.     }
    43.  
    44.     public int Defend()
    45.     {
    46.         int totalDefense;
    47.         totalDefense = (sloop.defense * numSloop) + // collect Defense * numer of current ships
    48.                       (corsair.defense * numCorsair) + // for each ship type
    49.                       (frigate.defense * numFrigate) +
    50.                       (carvahal.defense * numCarvahal) +
    51.                       (warship.defense * numWarShip);
    52.         totalDefense = Random.Range(0, totalDefense);
    53.         return totalDefense;// returns total Defense for fleet
    54.  
    55.     }
    56.  
    57.     public int Health()
    58.     {
    59.         int totalHealth;
    60.         totalHealth = (sloop.health * numSloop) + // collect health * number of current ships
    61.                       (corsair.health * numCorsair) + // for each ship type
    62.                       (frigate.health * numFrigate) +
    63.                       (carvahal.health * numCarvahal) +
    64.                       (warship.health * numWarShip);
    65.         return totalHealth;// returns total Health for fleet
    66.  
    67.     }
    68.  
    69. }
    sorry its such a long post, the ships class just stores an int for health, defense, and attack
     
  10. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    When you engage, you can get the script from the planet and from there you can retrieve values. Is that what you mean?
    I mean, it could be that your game works like: if fleet encounters planet fleet -> do combat calculations -> report results.
    I'm not sure..

    Do you want something like FleetsEngaged(Fleet fleet1, Fleet fleet2) { /* Do stuff */ }
    or something else?
     
  11. Smokeythebud

    Smokeythebud

    Joined:
    Aug 9, 2017
    Posts:
    34
    I have been working on this problem since I posted this and this is what I came up with
    Code (CSharp):
    1.  void OnTriggerEnter(Collider other)
    2.     {
    3.         if (other.gameObject.CompareTag("EnemyPlanet"))
    4.         {
    5.             Planet enemy = other.GetComponent<Planet>();
    6.             int attk = playerFleet.Attack();
    7.             if (attk > enemy.planetFleet.Defend())
    8.             {
    9.                 enemy.planetFleet.TakeDamage(attk);
    10.             }
    11.             else if (attk <= enemy.planetFleet.Defend())
    12.             {
    13.                
    14.                 playerFleet.TakeDamage(enemy.planetFleet.Attack());
    15.             }
    16.         }
    17.  
    18.     }
    that is the part of the player class I commented out, also added this to the fleet script
    Code (CSharp):
    1.  public void TakeDamage(int amount)
    2.     {
    3.         int rand = Random.Range(1, 6);
    4.         while (amount > 0)
    5.  
    6.             if (rand == 1)
    7.             {
    8.                 numSloop -= 1;
    9.                 amount -= sloop.health;
    10.             }
    11.             else if (rand == 2)
    12.             {
    13.                 numCorsair--;
    14.                 amount -= corsair.health;
    15.             }
    16.             else if (rand == 3)
    17.             {
    18.                 numFrigate -= 1;
    19.                 amount -= frigate.health;
    20.             }
    21.             else if (rand == 4)
    22.             {
    23.                 numCarvahal -=1;
    24.                 amount -= carvahal.health;
    25.             }
    26.             else if (rand == 5)
    27.             {
    28.                 numWarShip -= 1;
    29.                 amount -= warship.health;
    30.             }
    31.     }
    basically my game is this: fly to a planet which you can fight fleet vs fleet, if the planet fleet is destroyed the player owns that planet which will produce ships they can add to there fleet. In the end I intend to procedurally generate my planets in an area and make them steadily stronger as you get to the center when you capture the center planet it is game victory. it seems simple but I feel like I make everything too complicated. So I want it when they fight to remove the correct amount of ships from each fleet per battle. I may make this turn based or timer based I'm still unsure
     
  12. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    And is that working well for you?

    There's 1 tiny (unrelated issue) I see with your code. If you had incoming damage, of say '100'.
    Your warship is 80 and your frigate is 40. If the warship is hit, it's destroyed (good), now 'amount' should be 20, and if you hit the frigate, it's now killed the frigate instead of damaging it.
    Err, you're also only getting the random number once (making my sentence partially invalid). Dunno if that's on purpose or not :)

    Other than that, if it's working .. that's great :)
    Sounds like a fun game.
     
  13. Smokeythebud

    Smokeythebud

    Joined:
    Aug 9, 2017
    Posts:
    34
    The random number once was not intentional, is that due to my while loop? The intention was to make it work kind of in the reverse way I populated the planet fleet. I just didn't want to take attack vs defense subtract health, because I wanted to just destroy ships in the fleet which will reflect in the total health, after I can make these two objects and scripts interact correctly I want to make on collision a new scene which will be the battle and I'm thinking turn based is my best option for the battles. if I were to throw another if statement to check if amount is >= to whatever ship it's damaging before I destroy that ship that should fix my ships from dying from partial damage.
     
  14. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Yes, to the last part you wrote. If amount is less than their health, they'd be damaged but not destroyed.
    And yes, to the while loop. You only calculate the random # once, so each "attack (session)" would only kill off 1 type of ship. If you did the random number inside the loop, ... (random) types of ships would take damage from the attack ;)
     
  15. Smokeythebud

    Smokeythebud

    Joined:
    Aug 9, 2017
    Posts:
    34
    My code compiles perfectly, I got rid of the while loop and make my OnTriggerEnter into
    OnTriggerEnter2d and also Collider2d, but my code for the two fleets to fight never happened. I have my player collider as a very simple 5 point 2d polygon and my planets are 2d circle collides set as a trigger, but I can't seem to get the code to execute.
     
  16. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay, well does the OnTriggerEnter2D get called? One of them needs to have a rigidbody (for trigger, it can be kinematic or non-kinematic).
     
  17. Smokeythebud

    Smokeythebud

    Joined:
    Aug 9, 2017
    Posts:
    34
    I have a rigid body on my player, though honestly right now I can remember if it's a rigidbody2d, I put a debug.log in my on trigger function but it seems to never be called
     
  18. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay, well definitely check that you have the RIgidbody2D. :)

    Then, I'm not sure what to say if it's not called. Make sure the area is big enough? You can post some code if you think that will help/could be a problem?