- Home /
Accessing variable from parent
So I want to use 2 variables from another script in the child objects of 1 parent object, the variables are determined in that parent object, and I want only the child objects to be able to access these variables, how would I do this?
Answer by b1gry4n · Jun 02, 2018 at 08:04 AM
you can get all your children on the parent script while it is initializing and give the children scripts a reference to the parent script
ChildScript[] children = GetComponentsInChildren<ChildScript>();
foreach (ChildScript child in children)
{
child.parentReferenceScript = this;
}
and on the children, you use that reference
theValueIWant = parentReferenceScript.theValueIWant;
I did this with the only change being I replaced the names with the scripts and ints I want, but i'm getting these errors - A field initializer cannot refrence the nonstatic field, method, or property, ParentRefrenceScript.TheValueIWant1 | A field initializer cannot refrence the nonstatic field, method, or property, ParentRefrenceScript.TheValueIWant2 | Type ChildScript does not contain a definition for ParentRefrenceScript | I also added int before theValueIWant since I want it as an int value, if I don't do this it produces more errors.
Never $$anonymous$$d, just found out how to use GetComponentInParent, thanks for your help anyways.