在Unity中引用光源的问题 [英] Issues referencing a light in Unity
问题描述
我试图在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.
这是我的脚本,我将其附加到交通信号灯上.红绿灯的层次结构为:
This is my script, which I attached to the traffic light. The hierarchy of the traffic light is:
TrafficLight_A(基本交通信号灯)
TrafficLight_A (the base traffic light)
- 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"
我该怎么做才能解决此问题? (我对C#
有点陌生)
What can I do to fix this? (I'm somewhat new to C#
)
推荐答案
根据您的层次结构,您正试图从名为"RedLight"的GameObject中访问Light
组件,该GameObject是"TrafficLight_A" GameObject的子级.为此,使用"TrafficLight_A/RedLight"传递给GameObject.Find
函数,该函数先找到RedLight GameObject,然后再找到GetComponent<Light>()
来检索Light
组件.您可以在Awake
或Start
函数中做到这一点.
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;
}
这篇关于在Unity中引用光源的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!