Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by Tatsunomi · Aug 09, 2013 at 03:48 PM · variablesparentchildaccess

Accessing a variable from a child object and pass it to the parent

I've been checking around the forums for a solution for passing a variable from a child object to a parent object. I couldn't find the right way to do it... Either that or my Brain.exe has stopped working while i was debugging my code. I was trying to access a bool type variable from a child object's script and pass it to the parent Object's script.

Here's the code from the child script:

 using UnityEngine;
 using System.Collections;
 
 public class BlastArea : MonoBehaviour {
     public GameObject EBullet;
     RaycastHit hit;
     Transform Player;
     public bool attack = false;
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         Player = GameObject.FindGameObjectWithTag("Player").transform;
         Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forward), out hit);
         Debug.DrawLine(transform.position, Player.transform.position, Color.red);
         if(hit.collider.tag == ("Player")){
             Instantiate(EBullet,transform.position,transform.rotation);
             attack = true;
             Debug.Log(hit);
         }
         else{
             attack = false;
         }
     }
 }
 

Here's the Pic to show the hierarchy: alt text

The Parent Object is Tank with the script that needs to access the child object script BlastArea. The BlastArea script is linked to the Empty GameObject named BlastArea. I also tried doing this:

 public class TankParent : MonoBehaviour {
     Component attack;
     void Update () {
         //BlastArea attacking = attacking.GetComponent<BlastArea>().attack;
         //attackMode = attacking;
         attack = GetComponentInChildren<BlastArea>();
capture.png (2.8 kB)
Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jamora · Aug 09, 2013 at 04:22 PM 0
Share

In your TankParent script, shouldn't you use BlastArea ins$$anonymous$$d of Component? You could then query the attack bool directly by attack.attack. Have you tried this or as it not worked?

avatar image hitarthdoc1994 Jamora · Feb 08, 2016 at 12:24 PM 0
Share

We can't make a object of a $$anonymous$$ono Script. Then how are we supposed to Use Blast Area in any other way. I'm new to Unity so I might be wrong, Please correct me if I'm wrong.

avatar image Tatsunomi · Aug 09, 2013 at 04:35 PM 0
Share

How am I supposed to call BlastArea? Well... I do remember doing something similar to that but it didn't work for me.

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by IgorAherne · Aug 09, 2013 at 04:33 PM

well, you've done everything right;

let's say there are 2 scripts. You know that there is Update function and Start function.

there is a variable q that sits in script B. you will have to establish connection to script B and store it in script's A shortcut variable, say _shortcutFromAtoB; after this variable is given the link to script B, you can access any public variable in script B from script A using _shortcutFromAtoB.

Like this:

_shortcutFromAtoB.q

given that q is public in script B

     //script Test.cs
     using UnityEngine;
     using System.Collections;
     
     public class Test : Monobehavior{
         public bool q = false; //only contains 1 variable that can be either true or false
     }



//script accessor.cs

     using UnityEngine;
     using System.Collections;
     
     public class accessor : Monobehavior{
     
         Test _shortcutFromAccessorToTest;
         void Start(){
           _shortcutFromAccessorToTest = gameObject.GetComponentInChildren<Test>(); //you access the Test from the current gameObject and assign this shortcut to the shortcut variable that can hold data of type "Test"
          }
         
          void Update(){//and couple of examples of working with the variable from external script
     
         if( !  _shortcutFromAccessorToTest.q)
               _shortcutFromAccessorToTest.q = false;
         else 
             _shortcutFromAccessorToTest.q = true;
     
     
     
         Debug.Log(_shortcutFromAccessorToTest.q);
     }
     //one important note: the shortcut was established to the script, 
   //not to the variable, since right now we have a path to the instance of script. If we would attempt to store the external script's variable
  //in a shortcut, we would copy the VALUE and changing local shortcut wouldn't effect the external variable :<
     
     }
 
 
 
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by mononull · Aug 09, 2013 at 04:36 PM

 attack.attack = true; //or false

Using the code above this is what it would actually look like in the TankParent class. You want to get the component in TankParent, which in your case you said was 'attack' and then you want to access a boolean variable in BlastArea, which is also called 'attack'. You're on the right track here, but those names could get confusing. Also, be aware that you cannot create a reference to the boolean variable. Booleans are going to be passed by value and not by reference. You aren't doing that, but it looks like you may have been thinking along those lines. For example, saying boolean atk = BlastAreaScript.attack, would simply create a copy of the boolean value, so any changes to atk in this case would not be reflected in BlastAreaScript.attack. Value types like booleans and numbers and structs are by default passed by value, or copied, where more complex types like classes are passed by reference, or linked. So if we create a BlastArea type object and set it equal to an existing BlastArea object we are creating a reference to the existing one. They are the same existing object.

In your TankParent class I would call the component a different name, and maybe even change the type because I don't know how a generic Component type will behave for you. So where you have 'Component attack' change it to something like 'BlastArea BlastAreaScript', then set this variable equal to GetComponentInChildren(); I would also suggest moving the getcomponent command outside of your update function. That way you aren't searching for the script 100 times a second or whatever your frame rate is. Create a reference to it initially in a Start function or something of the like. Then since you created the reference you can access the script at any time granted the object was created in the class scope.

 public class TankParent : MonoBehaviour {
     //create the variable of BlastArea type
     BlastArea BlastAreaScript;
     void Start() {
        //set your variable equal to the component in the child
        //this creates a reference to it, a link to an already existing object
        BlastAreaScript = GetComponentInChildren<BlastArea>();
        //change the attack value from that script
        BlastAreaScript.attack = true; //or false
     }

Keep in mind since BlastAreaScript here is created on the class scope you can use it in any function of this class. So you can use the command 'BlastAreaScript.attack = true' anywhere you need it in the class.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Tatsunomi · Aug 09, 2013 at 04:55 PM 0
Share

I'm a little bit dazed but I think both your answer and Igor's is the same? Or maybe I'm a bit high... Well anyway thanks for the answer it helped but sadly I can't accept two answers so ins$$anonymous$$d I up voted your answer. Thanks again

avatar image mononull · Aug 09, 2013 at 05:07 PM 0
Share

Yeah I think we were typing our answers at the same time too. But I hope that helps. To answer your comment above "How am I supposed to call BlastArea?" Any class you write you can create an instance of it in your other scripts. So in your Tank script you can create an object of BlastArea type and then link it to the already existing BlastArea that is on the child object (in your case you linked using the getcomponentinchildren command). After linking, anywhere in your Tank script you can access the BlastArea script of the child without having to get the component again.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

18 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Make a simple tree 1 Answer

Calling parent variables from child and visa versa 1 Answer

Access a child from the parent or other gameObject. 2 Answers

Access parents other child from other other child 1 Answer

Trouble accessing child 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges