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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Int not being recognized when called in 'if' statement

Discussion in 'Scripting' started by DavidHenson, May 3, 2022.

  1. DavidHenson

    DavidHenson

    Joined:
    May 3, 2022
    Posts:
    4
    Code (csharp):
    1. {
    2.     // Start is called before the first frame update
    3.     void Start()
    4.     {
    5.         int shorp = 90;
    6.     shorp = shorp + 1;
    7.     print(shorp);
    8. // This is just me testing to make sure that the variable is recognized, it does show up in the console.
    9.    }
    10.     // Update is called once per frame
    11.     void Update()
    12.     {
    13.        if (Input.GetKeyDown("right"))
    14.     {
    15.         print(shorp);
    16.     }
    17.     }
    18. }
    19.  
    This is my current code, which gives me the error CS0103, saying "shorp" doesn't exist in the context, but I defined it at the start; can I make it recognize the variable without defining it in the if command? I don't want it to reset every single time I press the right arrow, I'd like to change it on the press.
     
    Last edited: May 4, 2022
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,951
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,571
    This:
    Code (CSharp):
    1. int shorp;
    declares a variable of type int and gives it the name "shorp". However you declared your variable inside the Start method. So it's a local variable that only exists inside Start. When Start has finished the variable doesn't exist anymore. You have to declare your variable as a member variable of your class. That means it has to be declared in the body of the class and not inside a method. You may look up the meaning of scope and extent of a variable.
     
  4. DavidHenson

    DavidHenson

    Joined:
    May 3, 2022
    Posts:
    4
    Thank you very much, this did fix the issue.