- Home /
Start a Coroutine in script A, from script B C#
I have my first script, called "IfLoose", A and my second script called "CollisionPlayer", B. I have a public void in sciprt A and i need to start it from script B. I have it so in script A, void includes stuff for having a animation play and stoping the time and i would like it to start when a collision occurs, in script B.
Here is script A:
using UnityEngine; using System.Collections;
public class IfLoose : MonoBehaviour {
bool AudioListener.pause;
public GameObject looseMenuPanel;
private Animator anim;
void Start () {
Time.timeScale = 1;
anim = looseMenuPanel.GetComponent<Animator>();
anim.enabled = false;
}
public void LooseGame(){
anim.enabled = true;
anim.Play("LooseMenu");
Time.timeScale = 0;
AudioListener.pause = true;
}
}
Script B:
using UnityEngine; using System.Collections;
public class CollisionPlayer : MonoBehaviour {
public void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Environment")
StartCoroutine ("LooseGame");
}
}
Thank you :D
Answer by Deathdefy · Feb 09, 2015 at 09:18 PM
Didn't test it but this should do the trick as long as you properly find the GameObject that you need.
public IEnumerator LoseGame()
{
//Add what you need here
return null;
}
public void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Environment")
{
//Find the gameobject with lfLoose attached to it
GameObject obj = GameObject.Find("ObjectToFind");
StartCoroutine(obj.GetComponent<lfLoose>().LoseGame());
}
}
Or, to rephrase, the name in quotes is a shortcut, which won't work for fancy stuff like coroutines in other scripts. The above is the "real" way to call a coroutine.
Then, to find a coroutine, its just the same "find something in another script" rules as anything else. Finding alice's coroutine is the same as finding alice's int hit points;
.
So what Deathdefy put is right? or wrong? and what srcipt would i put this in, A or B? Sorry for questions, im kinda a newbie :D
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
StartCoroutine in a public static void 1 Answer
Coroutine gets stuck randomly? 1 Answer
Yield not working properly 1 Answer