Execution Order of Statement is not corrent
Okay first of all give you a brief introduction of the function i created: its a function which checks wheather the net is working or not if net is working it fetch the image and set image.sprite Or if it is not working then gives a debug.log("Not working the net"); So Here is the function :
public void LoadImage()
{
StartCoroutine(CheckInternet());
//Call the actual loading method
if (isInternet == false)
{
StartCoroutine(RealLoadImage());
}
else
{
Debug.Log("No InternetConnection is Enable");
}
}
On Button Click Event this function is executed. Here is the function which checks the internet
IEnumerator CheckInternet()
{
WWW internet = new WWW("www.google.com");
yield return internet;
if (internet.error != null)
{
isInternet = false;
}
else
{
isInternet = true;
}
yield return null;
}
It check the light page forexample : google.com if it returns the google.com it means net is working but for my scenerio in function CheckInternet() WWW internet = new WWW("www.google.com"); yield return internet; it exits from here yield statement but it should countinue to next statement to make isInternet false or true. Thanks in advance :)
Answer by HenryStrattonFW · Nov 12, 2015 at 10:38 AM
The problem here is that you are not waiting for your internet connection check to finish before acting on the expected results.
StartCoroutine is used to start a process that may take 1 frame, or even several seconds to complete. Coroutines are often used for WWW requests because they very much asynchronous no matter how quick they can sometimes be.
In order to wait for your internet connection check to finish, you either need to run your LoadImage method as a coroutine as well, yielding on the StartCoroutine of the CheckInternet. OR pass a callback method into your check internet function, once the check is complete, it can then call the callback to act on the results. for example.
public void LoadImage()
{
StartCoroutine( CheckInternet( ( bool lHasInternet ) =>
{
if( lHasInternet )
{
Debug.Log( "We have a connection." );
// Trigger your image load.
}
else
{
Debug.Log( "No internet." );
}
} ) );
}
IEnumerator CheckInternet( System.Action<bool> lCallback )
{
WWW internet = new WWW( "www.google.com" );
yield return internet;
if( lCallback != null )
{
lCallback( string.IsNullOrEmpty( internet.error ) );
}
}
NOTE: However, is there any particular reason you are checking your connection this way instead of using something like a check on the value of Application.internetReachability ?
Your answer
Follow this Question
Related Questions
Asset Bundle not compatible between different unity versions 1 Answer
Overlap ScrollRect 1 Answer
Instantiating A group of platform and moving them down 0 Answers
CommandInvokationFailure: Unable to merge android manifests. ,Unable to merge android manifest Error 0 Answers
Unity 2D rotation not smooth? 0 Answers