- Home /
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?
GetComponentInChildren
will get the component in the current game object or the first one it finds in any of the children. if you want to modify all children, take a look at GetComponentsInChildren - note the plural...
also, if you're referencing the component more than once, consider caching it - the GetComponent
calls are relatively slow.
Ok, that is very helpful as well, mostly for semi-global variables. (Ones that multiple but not all objects share.)
Answer by DFT-Games · Oct 30, 2015 at 06:53 PM
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 :)
-Pino
Wow! Thank you so much, that works fantastically! It saves me a lot of hassle.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Need to use 2 different language scripts. 1 Answer
Basic C# Public Variable Help 3 Answers