I am trying to get information from a simple LDR light sensitive Resistor to trigger an audio clip in Unity 3D. I can get the clip to play but it overlaps and repeats the audio. What I want it to do is activate an audio clip from a random array of audio clips. How can I do this? This is the code I have.
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Threading;
public class Sending : MonoBehaviour {
//Random Clips
public AudioClip[] voices;
public GameObject worldLight;
public static Sending sending;
//public static SerialPort sp = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
public static SerialPort sp = new SerialPort("/dev/cu.wchusbserial1420", 115200);
public string message2;
void Awake () {
if (sending == null) {
DontDestroyOnLoad (gameObject);
sending = this;
} else if (sending != this) {
Destroy (gameObject);
}
}
float timePassed = 0.0f;
// Use this for initialization
void Start () {
OpenConnection();
}
// Update is called once per frame
void Update () {
//timePassed+=Time.deltaTime;
//if(timePassed>=0.2f){
//print("BytesToRead" +sp.BytesToRead);
message2 = sp.ReadLine();
print(message2);
// timePassed = 0.0f;
//}
if (message2!="") {
print("called");
lightMeUp(message2);
}
}
public void OpenConnection()
{
if (sp != null)
{
if (sp.IsOpen)
{
sp.Close();
print("Closing port, because it was already open!");
}
else
{
sp.Open(); // opens the connection
sp.ReadTimeout = 16; // sets the timeout value before reporting error
print("Port Opened!");
// message = "Port Opened!";
}
}
else
{
if (sp.IsOpen)
{
print("Port is already open");
}
else
{
print("Port == null");
}
}
}
void OnApplicationQuit()
{
sp.Close();
}
public static void sendYellow(){
sp.Write("y");
}
public static void sendGreen(){
sp.Write("g");
//sp.Write("
");
}
public static void sendRed(){
sp.Write("r");
}
public static void sendBlue(){
sp.Write("b");
}
public static void sendBlue2(){
sp.Write("1");
}
public static void sendPulse1(){
sp.Write("p");
}
public static void sendPulse2(){
sp.Write("q");
}
void lightMeUp(string message){
print (message);
float fl = float.Parse (message) / 100.0f;
fl = 1.0f - fl;
//Do Something
GetComponent<AudioSource> ().PlayOneShot (voices [Random.Range (0, voices.Length)]);
}
}