I need help with a Flashlight script
I have been trying to get my flashlight script to work yet, it keeps saying there is no light attach to the game object.
Here is the script:
using UnityEngine;
using System.Collections;
public class Flashlight : MonoBehaviour
{
public float a;
public float b;
public float c;
public float d;
public int batLevel;
public Light Flashlight;
public bool isOn;
public float timer;
void Start()
{
Flashlight = GetComponent<Light>();
batLevel = 101;
minusBat();
isOn = true;
}
void minusBat()
{
if (isOn)
{
batLevel -= 1;
}
}
void Update()
{
if (timer >= 0)
{
if (isOn)
{
timer -= Time.deltaTime;
}
}
if (timer <= 0)
{
timer = 5;
minusBat();
}
if (Input.GetKeyUp(KeyCode.F))
{
Flashlight.enabled = !Flashlight.enabled;
if (!isOn)
{
isOn = true;
}
else
{
isOn = false;
}
}
if (batLevel == 0)
{
batLevel = 0;
Flashlight.enabled = false;
isOn = false;
}
}
void OnGUI()
{
GUI.Box(new Rect(0, Screen.height / 1.21f, Screen.width / 6.16f, Screen.height / 19.58f), batLevel.ToString());
}
}
can someone tell me what i can do to fix this?
Answer by doublemax · Oct 17, 2016 at 09:31 PM
Flashlight = GetComponent<Light>();
If this finds no Light, it usually means that there is no Light component. Is the script attached to the light?
public Light Flashlight;
As this is public, did you drag a light (from another GameObject) into this variable? Then you must remove the line from above, because it will overwrite the content.
The script is not attached to the Light component, but to a modeled object that has the Light as a child, there is no light in the variable.
The script is not attached to the Light component, but to a modeled object that has the Light as a child
In that case GetComponent can't find the light. Use GetComponentInChildren ins$$anonymous$$d.
https://docs.unity3d.com/550/Documentation/ScriptReference/GameObject.GetComponentInChildren.html
Your answer

Follow this Question
Related Questions
Flashlight toggle 5 Answers
Light Probes - Need Help with one curious flashlight problem 0 Answers
Can anybody help me with a flashlight toggle script? 0 Answers
Flashlight script help! 2 Answers
how can I make my flashlight move with mouse movements 1 Answer