Calling a bool from another script doesn't seem to be working
I'm trying to have a piece of code run when a ball hits a trigger(to finish the stage) in an attempt to get the timer to stop running and add it to a score.
public class Finish_Cube : MonoBehaviour
public bool levelFin = false;
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
print("Level complete!");
levelFin = true;
}
}
public class Timer : MonoBehaviour
Finish_Cube finishCube;
public int time;
public bool _running;
public Text timerText, failText;
public int timeToScore;
private void Awake()
{
finishCube = GameObject.Find("FinishGameObject").GetComponent<Finish_Cube>();
}
void Start()
{
_running = true;
StartCoroutine(countdown());
failText.text = "";
}
IEnumerator countdown()
{
while (time > 0)
{
yield return new WaitForSeconds(1);
time -= 1;
}
failText.text = "LEVEL FAIL";
_running = false;
}
private void Update()
{
if (finishCube.levelFin) //here
{
StopAllCoroutines();
timeToScore = time;
print(timeToScore);
}
timerText.text = "Time: " + time.ToString();
}
What does not work? Are you sure the collision is detected? Have you any error in the console?
The collision is detected, this is tested by the print("Level complete!"). There are no errors in the console. For some reason, the if(finishCube.levelFin) { StopAllCoroutines(); timeToScore = time; print(timeToScore); }
doesn't seem to trigger
Are you sure finishCube
is referencing the correct script? $$anonymous$$aybe you have attached the script twice, and the one logging Level complete
is not the one referenced by your Timer instance. Add the following code to your Finish_Cube
class :
void Start()
{
Debug.Log( GetInstanceID() ) ;
}
// OnCollisionEnter function
print("Level complete! : " + GetInstanceID() );
And in your Timer
class:
private void Awake()
{
finishCube = GameObject.Find("FinishGameObject").GetComponent<Finish_Cube>();
Debug.Log(finishCube.GetInstanceID() ) ;
}
Answer by Larry-Dietz · Dec 05, 2017 at 07:24 AM
Are you receiving any errors with this code? Have you confirmed that finishCube = GameObject.Find("FinishGameObject").GetComponent(); is finding the game object, and getting the component?
If there is only one instance if an object with a Finish_Cube component, try changing that list to this...
finishCube = FindObjectOfType<Finish_Cube>();
See if that makes any difference.
Hope this helps, -Larry
Your answer
![](https://koobas.hobune.stream/wayback/20220612143947im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Randomizing and using Bool values 0 Answers
Destroy Problem 2 Answers
Local bool won't change inside coroutine 1 Answer
My Coroutine Ignores the Boolean 1 Answer
Help with coroutine crashing unity 1 Answer