- Home /
GetComponent in another script help
hi there
I have a problem and i can't figure out what the problem is.
I have a script with a var that I want to call in another script. I guess my coding is wrong cause i get this error "Assets/script asteroid.js(25,53): BCE0019: 'lives' is not a member of 'UnityEngine.Component'."
here is the var script called "script player"
var lives : int = 3;
here is the other script called "script asteriod"
function OnTriggerEnter (other : Collider)
{
if(other.gameObject.tag == "Player")
{
other.GetComponent("script player").lives -= 1;
}
}
any help will really be appreciated
Answer by GameVortex · Dec 12, 2013 at 11:07 AM
First of all, does your script actually have a space in its name? I will assume it does not, or at least it should not have.
When you use GetComponent with a string reference Unity does not know what type of object it is and just returns a Component instead. You will have to cast that component into the ScriptPlayer component:
scriptplayer player = other.GetComponent("scriptplayer") as scriptplayer;
player.lives -= 1;
or you could reference the type directly and you will not have to cast it:
//Notice the removal of the " symbols.
other.GetComponent(scriptplayer).lives -= 1;
Thx a lot, that really helped.. now i can continue coding.. Thx again.
Your answer
![](https://koobas.hobune.stream/wayback/20220613124011im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Assigning varaibles to prefabs 1 Answer
Declaring Variable in Child & Access as Parent 2 Answers
Adding joints through script 2 Answers
Change variable value of a script from another script. both in different Game object 1 Answer