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<Light>();
}
// 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<AudioSource>().isPlaying)
        {
            go.GetComponent<AudioSource>().Play();
        }
    }
}
private void SirenOff()
{
    foreach (GameObject go in sirens)
    {
        go.GetComponent<AudioSource>().Stop();
    }
}

}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值