Search Unity

FunctionCall from UIButton and Function Call by code give different results, use different spaces?

Discussion in 'Editor & General Support' started by SanjayBhambhu, Jun 29, 2019.

  1. SanjayBhambhu

    SanjayBhambhu

    Joined:
    Aug 22, 2012
    Posts:
    13
    This is something very strange, maybe I'm missing something because I've been coding since past 8 hours, but, simply put, this function:
    Code (CSharp):
    1.  
    2. public int avatarCategoryIndex = 0;
    3. public void PrintCheck()
    4. {
    5.             avatarCategoryIndex++;
    6.             Debug.Log("New Value = " + avatarCategoryIndex);
    7. }
    8.  
    9. private void Update()
    10. {
    11.             if (Input.GetKeyDown(KeyCode.K))
    12.                 PrintCheck();
    13. }
    14.  
    If the function PrintCheck() is called from Update() (by pressing K), then everything works fine, the value is printed as well as the value is visible in the inspector, next to the variable name.

    But, if the function PrintCheck() is called by a UI Button, the variable avatarCategoryIndex is incremented and printed, but THAT variable is somehow a separate variable. It is not increasing in the inspector. And the count doesn't continue from the one in the inspector. But a count is maintained. Subsuquent presses of that UI button show that the value is being stored somewhere as 1,2,3...

    It seems there's separate copies of this class stored in memory? How is this happening I am unable to understand.
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,282
    It looks like you have 2 instances of the component in the world. Did you also add one to the UIButton?
     
    SanjayBhambhu likes this.
  3. SanjayBhambhu

    SanjayBhambhu

    Joined:
    Aug 22, 2012
    Posts:
    13
    Yes, Indeed :D Thank You Sir
     
    karl_jones likes this.