问题
I'm trying to make a driving game in Unity, and as part of it, I'm trying to make a traffic light blink on and off.
This is my script, which I attached to the traffic light. The hierarchy of the traffic light is:
TrafficLight_A (the base traffic light)
- RedLight (the light I'm trying to make flash)
using UnityEngine;
using System.Collections;
public class Blink_Light : MonoBehaviour
{
public float totalSeconds = 2; // The total of seconds the flash wil last
public float maxIntensity = 8; // The maximum intensity the flash will reach
public Light myLight = Light RedLight; // The light (error)
public IEnumerator flashNow ()
{
float waitTime = totalSeconds / 2;
// Get half of the seconds (One half to get brighter and one to get darker)
while (myLight.intensity < maxIntensity) {
myLight.intensity += Time.deltaTime / waitTime; // Increase intensity
yield return null;
}
while (myLight.intensity > 0) {
myLight.intensity -= Time.deltaTime / waitTime; //Decrease intensity
yield return null;
}
yield return null;
}
}
However, I get an error:
Assets/Blink_Script/Blink_Light.cs: error CS1525: Unexpected symbol "RedLight"
What can I do to fix this? (I'm somewhat new to C#
)
回答1:
According to your hierarchy, you are trying to access a Light
component from a GameObject named "RedLight" which is a child of the "TrafficLight_A" GameObject. To do that, use pass "TrafficLight_A/RedLight" to the GameObject.Find
function which finds the RedLight GameObject then GetComponent<Light>()
to retrieve the Light
component. You can do that in the Awake
or Start
function.
Whenever you need to find a child object, the "/" is used just like you would in file path.
public float totalSeconds = 2; // The total of seconds the flash wil last
public float maxIntensity = 8; // The maximum intensity the flash will reach
public Light myLight;
void Awake()
{
//Find the RedLight
GameObject redlight = GameObject.Find("TrafficLight_A/RedLight");
//Get the Light component attached to it
myLight = redlight.GetComponent<Light>();
}
public IEnumerator flashNow()
{
float waitTime = totalSeconds / 2;
// Get half of the seconds (One half to get brighter and one to get darker)
while (myLight.intensity < maxIntensity)
{
myLight.intensity += Time.deltaTime / waitTime; // Increase intensity
yield return null;
}
while (myLight.intensity > 0)
{
myLight.intensity -= Time.deltaTime / waitTime; //Decrease intensity
yield return null;
}
yield return null;
}
来源:https://stackoverflow.com/questions/52765578/issues-referencing-a-light-in-unity