- Home /
Cant Get Componet From Script
I am having a small issue using the componet command from my C## script, my current script is javascript and I want the script to add health by using this command inside of my "PlayerHealth.Cs" file.
AdjustCurrentHealth(+10);
Both of my scripts are attached to my player but when I tried to use
var Script : PlayerHealth;
I get an error saying it cant find my PlayerHealth file.. so please and thank you! Stuck :/
GUI.skin = HEALTHPOT;
if (bagopen == true) {
if(GUI.Button (new Rect(Screen.width - Screen.width/8, Screen.height - Screen.height / 3.6, 64, 64), healthpots + "")) {
if ( healthpots >= 1) {
healthpots --;
}
}
}
Answer by Invertex · Jan 09, 2014 at 12:07 PM
If the script is on the same GameObject, then GetComponent in C# is fairly simple.
First you start by declaring a Component variable, this is the structure every time:
[modifier] [component name] [name we want this variable]
Like so:
private PlayerHealth playerHealth;
But that is not enough. We also need to declare on Start or Awake, that playerHealth is equal to the component we want. So we do:
playerHealth = GetComponent<PlayerHealth>();
And that's it! Now you can use the playerHealth component/script in your other script.
If the PlayerHealth script is not on the same object as this script, then you need to query the object it's on and GetComponent. One way is to do the same we did here, but on Start/Awake, we:
GameObject.Find("name of object PlayerHealth is on").GetComponent<PlayerHealth>();
This works perfect in C## but the script im using the code in is a javascript code! Can you tell me how to use this on javascript? Thanks !
I see you accepted the answer... Sorry I couldn't be more help, I rarely touch JS. Did you just convert the script to C#?
GetComponent("PlayerHealth"); // for js GetComponent(); // for c#
@edcarlo, looks like Unity strips the greater and less than signs sometimes haha.
Your answer
![](https://koobas.hobune.stream/wayback/20220613125927im_/https://answers.unity.com/themes/thub/images/avi.jpg)