I have a main class called Main, in that Main class there is an variable called State which is of int type. State variable contains a state ID which lets the program know in which state is it in (Menu, instructions screen…) In the Main class I have a object initiated from the Sprite class. Now my question is how to tell the object that the state has been switched (this one is easy, I can make this one pretty easily but the next part is giving me problems), and how can the object tell the Main class that he wants to switch states?
I have a main class called Main, in that Main class there is an
Share
This is what I understand from your question,
Mainis the controller class that invokesSpriteinstance methodsStatedetermines the method that is called on theSpriteinstanceIn this case, the
Spriteclass should contain a static property calledState(preferably this should be anenumrather than anint).It is the responsibility of the instance methods to update the state variable. On completion of execution of the instance method, the caller can check the state the instance is in and then appropriately determine the next course of action.
A better approach is not to expose the state at all (unless it is required to be used by external objects). In your case, it appears that the state is only being used to determines the method that executes (I am guessing that you have a
switchstatement to do this).If you want to instance to execute a particular method based on its own state, then you could leave this decision to the instance itself, rather than having the controller decide. The instance could have a method (say
Update()orExecute()) that execute the operation based on the context of the operation (like menu option, etc.). This method can decide which internal method to execute based on the staticstatemember.