user13142442
user13142442

Reputation:

How to call coroutine from another script? UNITY

This is the script where the touch action, the main game is on it

  var addingGoldPerSec = new GameObject();
    var buttonInstance = addingGoldPerSec.AddComponent<ItemButton>();
    StartCoroutine(buttonInstance.addGoldLoop());

And this is the one where I have the coroutine

public double goldPerSec
{
    get
    {
        if (!PlayerPrefs.HasKey("_goldPerSec"))
        {
            return 0;
        }
        string tmpStartGoldPerSec = PlayerPrefs.GetString("_goldPerSec");
        return double.Parse(tmpStartGoldPerSec);
    }
    set
    {
        PlayerPrefs.SetString("_goldPerSec", value.ToString());
    }
}

public void updateUI()
{
        priceDisplayer.text = LargeNumber.ToString(currentCostPerSec).ToString();
        coinDisplayer.text = "PER SEC\n" + LargeNumber.ToString(goldPerSec).ToString();
        levelDisplayer.text = "LEVEL\n" + level + "/150".ToString();
}
public IEnumerator addGoldLoop()
{
    while (DataController.Instance.gold <= 1e36)
    {
        DataController.Instance.gold += goldPerSec;
        if (Gameplay.Instance.booster == 1)
        {
            yield return new WaitForSeconds(0.25f);
        }
        else if (Gameplay.Instance.booster == 0)
        {
            yield return new WaitForSeconds(1.0f);
        }
    }
}

And this is a third Script where I manage the data stored into PlayerPrefs

 public void loadItemButton(ItemButton itemButton)
{
    itemButton.level = PlayerPrefs.GetInt("_level",1);
    PlayerPrefs.GetString("_costPerSec", itemButton.currentCostPerSec.ToString());
    PlayerPrefs.GetString("_goldPerSec",itemButton.goldPerSec.ToString());
}
public void saveItemButton(ItemButton itemButton)
{
    PlayerPrefs.SetInt("_level", itemButton.level);
    PlayerPrefs.SetString("_costPerSec", itemButton.currentCostPerSec.ToString());
    PlayerPrefs.SetString("_goldPerSec", itemButton.goldPerSec.ToString());
}

I have the second script which is the coroutine one attached into several gameobjects where exists an Upgrade button, per upgrade increases the coin by second you earn, the main problem here is that the coroutine just stops after I touch the screen, so I made another code into the main script so by that way the coroutine will keep working even after touched the screen, so I made a script where is the GameObject, but it just throws me NullReferenceException, tried a check with TryCatch and throws me that the problem is coming from the GameObject that I have created on the main script, but if is that way I need to attach to the main object where the main script exists, like more than 10 gameobjects where the coroutine exists, I think Singleton is not the way, it deletes me all the information above there by instantiating on Awake, I never thought about making static so I did as you told me and I need to change almost of my code, every text is attached into each gameobjects, to make a non-static member work with a static-member need to delete Monobehaviour but it just makes the game explode, thanks for helping me.

Upvotes: 1

Views: 8704

Answers (1)

Frenchy
Frenchy

Reputation: 17017

Create two scripts and attach them, for example, at Main Camera. The first script contains your timer with all variables:

using UnityEngine; using System.Collections;

public class TimerToCall : MonoBehaviour {
 //Create your variable
 ...
 //Your function timer
 public IEnumerator Counter() {
  ...
 }
}

In the second script, you will call the timer:

public class callingTimer : MonoBehaviour {
 void Start() {
  //TimerToCall script linked to Main Camera, so
  StartCoroutine(Camera.main.GetComponent<TimerToCall>().Counter());
 }
}

if you want to have for example the second script not linked to any gameObjet you could use static property:

in first script linked:

void Start()
{
    StartCoroutine(CallingTimer.ExampleCoroutine());   
} 

in second script not linked, you use the static property:

using System.Collections;
using UnityEngine;

public class CallingTimer
{
    public static IEnumerator ExampleCoroutine()
    {
        //Print the time of when the function is first called.
        Debug.Log("Started Coroutine at timestamp : " + Time.time);

        //yield on a new YieldInstruction that waits for 5 seconds.
        yield return new WaitForSeconds(5);

        //After we have waited 5 seconds print the time again.
        Debug.Log("Finished Coroutine at timestamp : " + Time.time);
    }
}

Upvotes: 1

Related Questions