How to use GetComponentsInChildren? (C#)

I’m trying to create a sort of global variable for my project, and apparently the best way to do this is to put everything under an empty parent object and have the parent object change it for everyone. So I havee this code:

void Update () {

		if (parentLevel > 0) {
			GetComponentInChildren<ClickAway>().currentChoiceID = currentChoiceID;
			GetComponentInChildren<ClickAway>().perspectiveSpanish = perspectiveSpanish;
		}`

But the variables are not changing in the children? How exactly does this function work? Am I using it wrong?

Hi @RothX,

To implement project-wide variables you don’t need to use any scene object. All you need is a static class exposing static members. Here’s a step by step solution (the simplest possible one).

  • Create a new sript and name it something like MyVariables.cs

  • Edit this script, deleting all its content and replacing it with this:

    public static class MyVariables
    {
    public static int CurrentScore { get; set; }
    }

  • Save the file

Now from anywhere in your code you can simply write

            MyVariables.CurrentScore = 10;

or use it in any other way and it will just work.

Hope this helps :slight_smile:

-Pino