unity关于警报灯光与警报声音的参考代码

初学。。总结回顾使用,希望给点建议。

首先,创造所需要灯光,直射光,设置颜色亮度等。
加上脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class alarmlight : MonoBehaviour {

public bool alarmOn;
private new Light light;
private static alarmlight instance;
public float animationSpeed = 2;
private float lowintensity = 0;
private float highintensity = 2;

public float targetintensity;

public static alarmlight Getinstance
{
    get
    {
        if (instance == null)
        {
            instance = new alarmlight();
        }
        return instance;
    }
}
// Use this for initialization
private void Awake()
{
    targetintensity = highintensity;
}
private void Start()
{
    alarmOn = false;
    instance = this;
    light = this.GetComponent();
}
// Update is called once per frame
void Update () {
    if(alarmOn)
    {
        light.intensity = Mathf.Lerp(light.intensity, targetintensity, Time.deltaTime * animationSpeed);
        if (Mathf.Abs(light.intensity - targetintensity) < 0.2)
        {
            if (targetintensity == highintensity)
            {
                targetintensity = lowintensity;
            }else if(targetintensity == lowintensity)
            {
                targetintensity = highintensity;
            }
        }
    }
    else
    {
        light.intensity = Mathf.Lerp(light.intensity, 0, Time.deltaTime * animationSpeed);
    }

}

}

主要是通过Mathf.Lerp函数实现对light.intensity的调整,使其在0-2中波动,在距离目标小于0.2时,改变目标变化值(0和2)。达到一个目的,使其通过alarmOn来控制灯光闪动。

另加脚本,在游戏流程控制物体上添加。使上面的alarmOn等于本脚本中的alarmOn,
在场景中加入几个警报声音,通过GameObject.FindGameObjectsWithTag(“siren”);进行获取,得到一个数组sirens,
并实现当alarmOn触发时,调用函数遍历每一个audio source使声音播放。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gamecontrol : MonoBehaviour {

private GameObject[] sirens;
public bool alarmOn;


// Use this for initialization
private void Awake()
{
    sirens = GameObject.FindGameObjectsWithTag("siren");
    alarmOn = false;
}

void Start () {

}

// Update is called once per frame
void Update () {
    alarmlight.Getinstance.alarmOn=this.alarmOn;
    if(alarmOn)
    {
        SirenOn();
    }
    else
    {
        SirenOff();
    }
}

private void SirenOn()
{
    foreach(GameObject go in sirens)
    {
        if(!go.GetComponent().isPlaying)
        {
            go.GetComponent().Play();
        }
    }
}
private void SirenOff()
{
    foreach (GameObject go in sirens)
    {
        go.GetComponent().Stop();
    }
}

}

你可能感兴趣的:(Unity,案列学习总结,unity脚本,灯光警报)