Такой метод раочий?
Создать пустой объект, добавить к нему AudioSource и прикрепить два скрипта:
для микрофоного ввода:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class PureMicrophone : MonoBehaviour {
public float sensitivity = 100;
public float loudness = 0;
AudioSource src;
void Start() {
src = GetComponent<AudioSource>();
}
void Update(){
loudness = GetAveragedVolume() * sensitivity;
}
float GetAveragedVolume()
{
float[] data = new float[256];
float a = 0;
foreach(float s in data)
{
a += Mathf.Abs(s);
}
return a/256;
}
}
и второй скрипт для генерации объектов по звуку:
using System.Collections;
public class SpawnByLoudness : MonoBehaviour {
public GameObject audioInputObject;
public float threshold = 1.0f;
public GameObject objectToSpawn;
PureMicrophone micIn;
void Start() {
if (objectToSpawn == null)
Debug.LogError("You need to set a prefab to Object To Spawn -parameter in the editor!");
if (audioInputObject == null)
audioInputObject = GameObject.Find("AudioInputObject");
micIn = (PureMicrophone ) audioInputObject.GetComponent("MicrophoneInput");
}
void Update () {
float l = micIn.loudness;
if (l > threshold)
{
Vector3 scale = new Vector3(l,l,l);
GameObject newObject = (GameObject)Instantiate(objectToSpawn, this.transform.position, Quaternion.identity);
newObject.transform.localScale += scale;
}
}
}
версия юнити 5.1.2
пишет ошибку NullReferenceException: Object reference not set to an instance of an object
SpawnByLoudness.Update () (at Assets/SpawnByLoudness.cs:18)
показывает на float l = micIn.loudness; (18 строчка кода)
буду очень признателен если подскажете, как сие исправить