Hey guys. I know this question has been asked a billion times, but I can’t seem to find the info I need. I’m trying to make a script where when the Player clicks a flashlight, the flashlight activates the flashlight script attached to the player while the model that the Player clicks destroys itself. While the model is destroyed, the script doesn’t activate. Any help?
var Flashlight : Flashlight;
function Start() {
Flashlight = GetComponent<Flashlight>();
}
function OnMouseDown() {
Flashlight.enabled = true;
Destroy(gameObject);
}
Hi @GraviterX,
Try changing the Flashlight variable representative to a lower case “f”. Unity is probably getting your variable confused with the component. Is the word Flashlight (variable) a different color? If so, then problem solved 
var flashlight : Flashlight
EDIT
Also, always use lower case letters for first words of custom variables. If you don’t, at some point it could be the same name as a script or something already taken, then you’ll have to change everything.
Also, it would be great if you would accept this answer if it helped 
var flashlight : Flashlight;
function Start() {
//GetComponent<Type>() is used in C#, while GetComponent(Type) is used in JS
flashlight = GameObject.FindWithTag("Player").GetComponent(Flashlight);
}
function OnMouseDown() {
flashlight.enabled = true;
//Also, this line will cause troubles
Destroy(gameObject);
}
I found two errors in the code. The first is the GetComponent()
call. It was an easy fix. The second problem that you would run into is that your Flashlight component would end up being destroyed along with the GameObject it’s attached to. flashlight
is a component on the GameObject (according to the code) and Destroy(gameObject)
is called, destroying the GameObject and the components.
However, you stated that you would like the Flashlight
component on the player to be enabled, correct? If so, you should tag the player as “Player” or something similar and change the line flashlight = GetComponent(Flashlight);
to flashlight = GameObject.FindWithTag("Player").GetComponent(Flashlight);
Hope it works!
This line:
Flashlight = GetComponent<Flashlight>();
Should look like this:
Flashlight = GetComponent.<Flashlight>();
if you want to use the generic version of GetComponent. Note the dot after GetComponent. With this you won’t get those compiler errors.