c# - How can I change an instance variable from within a static method? -


i implementing unity3d ads android game. i'm using helper class unity provides manage different events.

if user watches video , completes it, reward user play money(candy). method called after video ad has been initialized:

private static void handleshowresult (showresult result)     {         switch (result)         {         case showresult.finished:             debug.log("the ad shown.");              break;         case showresult.skipped:             debug.log("the ad skipped before reaching end.");             break;         case showresult.failed:             debug.logerror("the ad failed shown.");             break;         }     } 

in class comments says should customize method perform actions based on whether ad shown or not.

if ad shown want update user's candy. here candymanager class updates candy user collects or earns in game:

[system.serializable] public class candymanger : monobehaviour {      // start     public text candybartext;      public text candybartextshadow;      // play     public text candybartext2;      public text candybartextshadow2;      public int candy;       void update(){         candybartext.text = "" + candy;         candybartextshadow.text = "" + candy;          candybartext2.text = "" + candy;         candybartextshadow2.text = "" + candy;     } } 

what able update candy within static handleshowresult():

candymanager.candy = candymanager.candy + 5;

"candymanager" current instance of candymanager class

if can't update instance variable static method, how can update when video shown?

first off, there nothing stopping performing operations on instanced object static method, in fact, if static method in different class, there no difference in need in order perform operation.

that requirement simple, need have reference instance of object wish perform operation on. special thing static doesn't have access this reference/pointer regarding class members, still need reference instance work, whereas normal class member can use this (usually implicitly).

so, find object , candymanager component, , call normally:

//in static method gameobject.find("mymanagerobject").getcomponent<candymanager>().updatecandy(value); 

or that. in other technologies, (or in unity) can pass reference static method. noted in comments, static class raise event candymanager listens for.


Popular posts from this blog