Search Unity

Where to initialize variables in C#

Discussion in 'Scripting' started by Ultermarto, Mar 30, 2014.

  1. Ultermarto

    Ultermarto

    Joined:
    May 10, 2013
    Posts:
    31
    Hey people. So when I program in C++, if there's any variable that I want to be constant, I just declare it outside of the main loop. That way, it doesn't get reset every time the loop does. The loop can still access all of my variables because it is declared within their scope, like this:

    Code (csharp):
    1.  
    2. void main()
    3. {
    4.    int playerHp = 10;   // Variable that I don't want to change.
    5.    int gameTime = 0;   // Variable that I do want to change.
    6.  
    7.    while(gameRunning == true)
    8.    {
    9.       cout << playerHp << endl;
    10.       gameTime++;
    11.    }
    12. }
    13.  
    In the C# template in unity, it provides the Start() function for initializing variables, and the Update() function for running the game. If I want to declare and store variables that I don't want to be changing constantly, I have to declare them in the Start() function. This means that they're out of scope of the Update() function, which is where most of my game will be happening. Am I supposed to pass the Start variables to the Update function or something? How do I do that? Or is there another way?
     
  2. Badams66

    Badams66

    Joined:
    Mar 11, 2014
    Posts:
    49
    You do not have to declare variables in the start function. You can initialize them in your class
     
    Last edited: Apr 8, 2014
  3. Jakob_Unity

    Jakob_Unity

    Joined:
    Dec 25, 2011
    Posts:
    269
    put them in the class - making them public in the template will make them appear in the default inspector.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Example : MonoBehaviour {
    6.     public int playerHp = 10;  // Variable that I don't want to change.
    7.     public int gameTime = 0;   // Variable that I do want to change.
    8.    
    9.     void Start () {
    10.     }
    11.    
    12.     void Update () {
    13.     }
    14. }
     
  4. Ultermarto

    Ultermarto

    Joined:
    May 10, 2013
    Posts:
    31
    Oh. Could've sworn that was illegal. Thanks.