[英]Issues referencing a light in Unity
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. 我试图在Unity中制作一个驾驶游戏,并且作为其中的一部分,我试图使一个红绿灯闪烁。
This is my script, which I attached to the traffic light. 这是我的脚本,我将其附加到交通信号灯上。 The hierarchy of the traffic light is:
交通信号灯的层次结构为:
TrafficLight_A (the base traffic light)
TrafficLight_A(基本交通信号灯)
- RedLight (the light I'm trying to make flash)
RedLight(我要闪光的灯)
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#
) (我是
C#
新手)
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. 根据您的层次结构,您正在尝试从名为“ RedLight”的GameObject中访问
Light
组件,该游戏对象是“ 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. 为了做到这一点,使用通行证“TrafficLight_A /红灯”到
GameObject.Find
其中找到红灯游戏物体然后函数GetComponent<Light>()
来检索Light
组件。 You can do that in the Awake
or Start
function. 您可以在“
Awake
或“ Start
功能中执行此操作。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.