- Home /
How to start a Coroutine in another Script?
Dear Community,
I try to write a function which starts a Coroutine in aother Script after pressing the ArrowDown Key. After running the Script it says:
NullReferenceException.
Here is my simple Code:
First Script:
public class Player : MonoBehaviour
{
PlayerControll playerControll = new PlayerControll();
private void Update ()
{
PlayerNavigating();
}
private void PlayerNavigating()
{
playerControll.SetInputControll();
}
}
Second Script:
public class PlayerControll : MonoBehaviour
{
internal void SetInputControll()
{
if (Input.GetKeyUp(KeyCode.DownArrow))
{
StartCoroutine("testCo");
}
}
IEnumerator testCo()
{
Debug.Log("IN COROUTINE");
yield return null;
}
}
How I can write the code propetly to start the coroutine in the second script?
Answer by TheSOULDev · Sep 30, 2017 at 07:32 PM
First of, don't use strings to call a coroutine. Secondly, make the function you're calling private and make sure that the gameobject that the script you're calling is instantiated to an instance. From what I see your reference is empty.
Answer by bolkay · Sep 30, 2017 at 07:34 PM
@Patryk1899. I think your second script should derive or inherit from the Player class in the first script.
public class PlayerControll: Player
//instead of
//public class PlayerControll:Monobehaviour
Your answer
Follow this Question
Related Questions
I can't start a coroutine. I get a weird message from visual studio 1 Answer
NullReferenceException: Object reference not set to an instance of an object 3 Answers
Had difficulties implementing intro to Coroutines from unitypatterns.com. Help? 1 Answer
Coroutine sequence not running properly 1 Answer
Does UnityEngine.CustomeYieldInstruction works in a seperate thread? 2 Answers