- Home /
Static function, coroutine and trying to access an instance
Hiya, I have a static function issue/ IEnumerator issue. I have a static function called RegisterSelection:
public static void RegisterSelection (GameObject objectToRegister)
{
//code
StartCoroutine ( MoveAndCheckForMatch () );
}
…within this function I"m trying to execute StartCoroutine called MoveAndCheckForMatch as you can see.
private IEnumerator MoveAndCheckForMatch ()
{
//code
}
And I guess you know what's coming. Initially the compiler was complaining that 'an object reference is required to access non-static member SphereController.MoveAndCheckForMatch etc etc I understand this to be the case, as coroutines can only run on instances of monobehaviours
SphereController is attached to a gameobject in the world, so after reading the forums I tried to get access to an instance of the script:
instanceReference = GameObject.Find("Controller").GetComponent<SphereController>();
and tried to change how I'm calling the coroutine to
instanceReference.StartCoroutine ( MoveAndCheckForMatch () );
However I'm still getting the same issue. I know this is a commonly asked question on the forums, but I understood that i was following the suggested solution, but I'm clearly messing up somewhere!
Thanks in advance for any assistance.
I apologise for this incredibly slow moderation queue today. It's been offline for the last 14 hours or so, and this is the first moment I've been able to access it to clear people's post!
Answer by syclamoth · Dec 04, 2011 at 06:19 AM
The problem here is that 'MoveAndCheckForMatch' is a private member of SphereController, meaning you can't access it from outside! Instead, you should expose a public method which can be called directly, and then passes the message on.
public void StartMoveAndCheck()
{
StartCoroutine(MoveAndCheckForMatch());
}
instanceReference.StartMoveAndCheck();
Static functions are a little bit annoying to get working in an object-oriented sense, since they kind of fly in the face of everything oop stands for. You should avoid them when you can.
thanks for your response, but I don't think this is the solution - it's not a question of visibility within the class (I can change the $$anonymous$$oveAndCheckFor$$anonymous$$atch to public) it's the fact that it needs an instance as it's a coroutine, which I thought 'instanceReference = GameObject.Find("Controller").GetComponent();' would resolve.