- Home /
How can i acces a component belonging to one gameObject from a second gameObject?-in Javascript
I have a camera and i need to access some if its variables from a script on my main character. i have no idea how to refer to another object and its components in javascript.
Answer by fransh · Jul 25, 2013 at 10:52 PM
Presume your main character is called "Player1", and this gameobject got a script called "Player1Script" and this script got a function named "DieNow" that you want to call for example.
gameObject.Find("Player1").GetComponent("Player1Script").DieNow();
Or, the player loses a life and you just need to change the hitPoints var on that player.
gameObject.Find("Player1").GetComponent("Player1Script").hitPoints -= 1;
Of course if you are going to call those functions more often, it is rather useful to store the Player1 gameObject in a var, and the same goes for the Player1Script located on the player.
Answer by Quantum2 · Jul 25, 2013 at 10:48 PM
Make a public GameObject variable and assing the game object in the editor, then you can just use the script to acess the "external" game object components
Your answer
![](https://koobas.hobune.stream/wayback/20220613110853im_/https://answers.unity.com/themes/thub/images/avi.jpg)