Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by Extremo · Oct 29, 2010 at 10:56 PM · coroutineserverweb

How to access StartCoroutine in a static way

Hello, I got this small problem. I am using StartCoroutine for a www request but I can't figure a work-around to access it in a static way. Here is a sample code of what I do:

public static void mysql_query(string sServer, string sQuery)
    {
        sQuery = WWW.EscapeURL(sQuery);
        www = new WWW(sServer+"?Query="+sQuery);
        StartCoroutine(WaitForRequest(www));
        if(www.error == null)
        {
            ResultSet = www.text;
        }
        else
        {
            Debug.Log("Error at: "+ www.error);
        }
    }

My problem is that StartCoroutine is obviously a non static method. I can't seem to figure out a work-around to access it in a none static way.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
7

Answer by Tetrad · Oct 29, 2010 at 11:17 PM

Just give it a dummy gameobject to run on. Maybe put a script on that gameobject that gives you singleton-style access to it. You should then be able to do something like dummyComponent.StartCoroutine( whatever );

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ina · Apr 15, 2012 at 10:39 PM 2
Share

that seems a very inelegant and roundabout way of doing it

avatar image cregox · Jul 10, 2012 at 02:29 PM 0
Share

you said "roundabout"

avatar image Bunny83 · Jul 10, 2012 at 02:45 PM 0
Share

@cawas: This comment is pretty useless... Do you want to point out "roundabout (indirect)" isn't a proper word in this case?

avatar image cregox · Jul 23, 2012 at 03:10 PM 0
Share

@bunny83 finally unity $$anonymous$$m let me comment again (many migration issues with UDN I had)! nope, it's just useless indeed. shouldn't bother you so much, tho. you could say something funny back ins$$anonymous$$d. ;-)

avatar image
3

Answer by cregox · Aug 14, 2013 at 04:20 PM

If you don't have at least 1 singleton in your whole project already, get one. And use it like Tetrad already said:

 MySingleton.StartCoroutine( MyCoroutine);

Here's my favorite singleton implementation so far, I adapted from "50 tips for working with Unity" (currently broken link, so here's the google cache):

 using UnityEngine;
 
 /// <summary>
 /// Be aware this will not prevent a non singleton constructor
 ///   such as `T myT = new T();`
 /// To prevent that, add `protected T () {}` to your singleton class.
 /// </summary>
 public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
 {
     private static T _instance;
     
     private static object _lock = new object();
     
     public static T Instance
     {
         get
         {
             if (applicationIsQuitting) {
                 Debug.LogWarning("[Singleton] Instance "+ typeof(T) +
                 " already destroyed on application quit." +
                 "Won't create again - returning null.");
                 return null;
             }
             
             lock(_lock)
             {
                 if (_instance == null)
                 {
                     _instance = (T) FindObjectOfType(typeof(T));
                     
                     if (_instance == null)
                     {
                         GameObject singleton = new GameObject();
                         _instance = singleton.AddComponent<T>();
                         singleton.name = "(singleton) "+ typeof(T).ToString();
                         
                         DontDestroyOnLoad(singleton);
                         
                         Debug.Log("[Singleton] An instance of " + typeof(T) + 
                             " is needed in the scene, so '" + singleton +
                             "' was created with DontDestroyOnLoad.");
                     } else {
                         Debug.Log("[Singleton] Using instance already created: " +
                             _instance.gameObject.name);
                     }
                 }
                 
                 return _instance;
             }
         }
     }
     
     private static bool applicationIsQuitting = false;
     /// <summary>
     /// When unity quits, it destroys objects in a random order.
     /// In principle, a Singleton is only destroyed when application quits.
     /// If any script calls Instance after it have been destroyed, 
     ///   it will create a buggy ghost object that will stay on the Editor scene
     ///   even after stopping playing the Application. Really bad!
     /// So, this was made to be sure we're not creating that buggy ghost object.
     /// </summary>
     public void OnDestroy () {
         applicationIsQuitting = true;
     }
 }

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image JanVog · Nov 04, 2015 at 08:57 PM 0
Share

I don't quite understand the usage of singletons.. I added the singleton script to my StandardAssets Folder, created a $$anonymous$$anager script as told and put my coroutine in there (called FadeOut), he gives me the following error:

"The body of $$anonymous$$anager.fadeOut(UnityEngine.UI.Text, float, UnityEngine.Color)' cannot be an iterator block because void' is not an iterator interface type"

I have no idea what this error wants to tell me.. help!! And could you please tell me how to use singleton right, too?

avatar image
3

Answer by brunoleos · Feb 17, 2017 at 09:12 AM

If you don't want a singleton (because your code can become very dependent on them, which makes it difficult to refactor) nor using dummy GameObjects (because you have to create/manage them), you can pass a MonoBehaviour as argument to your static method, and them call StartCoroutine from it.

If you call the static method from a script (Monobehaviour-based object attached to GameObject), you can call the static method using the "this" keyword:

Example static method:

 public class Utility
     {
         public static void mysql_query(string sServer, string sQuery, MonoBehaviour justToStartCoroutine)
         {
             sQuery = WWW.EscapeURL(sQuery);
             www = new WWW(sServer + "?Query=" + sQuery);
             justToStartCoroutine.StartCoroutine(WaitForRequest(www));
             if(www.error == null)
             {
                 ResultSet = www.text;
             }
             else
             {
                 Debug.Log("Error at: " + www.error);
             }
         }
     }

Example call at YourScript.cs:

 public class YourScript : MonoBehaviour
     {
 // Class members
 
         void Start()
         {
             Utility.mysql_query("", "", this);
         }
     }


Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

How can I send and receive data to and from a URL, i.e. server side scripts, web services, etc? 3 Answers

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

How can i receive data from URL like cookies? 0 Answers

yield on WWW? or AssetBundleRequest? or both? 2 Answers

Making a fill take exactly n seconds to complete 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges