Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //this is all psuedotype -- not tested or anything, but hopefully it's easy enough to follow
- //unity stuff
- //scriptname monobehavior etc
- //custom class
- public class PianoKey
- {
- public bool isPressed = false;
- public float pitch = 0.5f;
- public AudioSource audioSource;
- PianoKey(float Pitch)
- {
- pitch = Pitch;
- }
- }
- PianoKey[] pianoKeys;
- PianoKeyScript[] pianoKeyScripts;
- public GameObject pianoKeyPrefab;
- //to use in this script, you can do something like
- void Start()
- {
- pianoKeys = new PianoKey[keyCount];
- for(int i = 0; i < pianoKeys.Length; i++)
- {
- //create new pianokey with specified pitch (from an array of pitches or whatever)
- pianoKeys[i] = new PianoKey(pitches[i]);
- //as i started writing this, I realized it'd be better to use a prefab and instead of having a PianoKey class in here, just create its own script for it and have it live on the prefab.
- //the prefab would have the audiosource already, and you could set up the references to the audiosource in the inspector
- //then you'd instantiate it like this
- GameObject newPianoKey = Instantiate(pianoKeyPrefab, Vector3.zero, Quaternion.identity) as GameObject;
- pianoKeyScripts[i] = newPianoKey.GetComponent<PianoKey>();
- //and since the array is an array of the monobehavior, you could do stuff like
- pianoKeyScripts[i].audio.Play();
- pianoKeyScripts[i].isPressed = true;
- }
- }
- void Update()
- {
- for(int i = 0; i < pianoKeys.Length; i++)
- {
- if(pianoKeys[i].isPressed)
- {
- //play audio source if already not playing
- if(!pianoKeys[i].audioSource.isPlaying)
- pianoKeys[i].audioSource.Play();
- }
- else
- {
- //stop audio source if playing
- if(pianoKeys[i].audioSource.isPlaying)
- pianoKeys[i].audioSource.Stop();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement