在Unity中引用光源的问题

时间:2018-10-11 17:11:05

标签: c# unity3d light

我正在尝试在Unity中制作一个驾驶游戏,作为其中的一部分,我正在尝试使一个红绿灯闪烁。

这是我的脚本,我将其附加到交通信号灯上。红绿灯的层次结构为:

  

TrafficLight_A(基本交通信号灯)

     
      
  • 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;
     }
 }

但是,我得到一个错误:

Assets/Blink_Script/Blink_Light.cs: error CS1525: Unexpected symbol "RedLight"

该如何解决? (我对C#有点陌生)

1 个答案:

答案 0 :(得分:2)

根据您的层次结构,您正尝试从名为“ RedLight”的游戏对象(它是“ TrafficLight_A”游戏对象的子代)访问Light组件。为此,请使用传递“ TrafficLight_A / RedLight”到GameObject.Find函数,该函数先找到RedLight GameObject,然后再找到GetComponent<Light>()以检索Light组件。您可以在AwakeStart函数中做到这一点。

每当需要查找子对象时,都使用“ /”,就像在文件路径中一样。

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;
}