Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1. //this is all psuedotype -- not tested or anything, but hopefully it's easy enough to follow
  2.  
  3. //unity stuff
  4. //scriptname monobehavior etc
  5.  
  6. //custom class
  7. public class PianoKey
  8. {
  9.     public bool isPressed = false;
  10.     public float pitch = 0.5f;
  11.     public AudioSource audioSource;
  12.    
  13.     PianoKey(float Pitch)
  14.     {
  15.         pitch = Pitch;
  16.     }
  17. }
  18.  
  19.  
  20. PianoKey[] pianoKeys;
  21. PianoKeyScript[] pianoKeyScripts;
  22.  
  23. public GameObject pianoKeyPrefab;
  24.  
  25. //to use in this script, you can do something like
  26.  
  27.  
  28. void Start()
  29. {
  30.  
  31.     pianoKeys = new PianoKey[keyCount];
  32.     for(int i = 0; i < pianoKeys.Length; i++)
  33.     {
  34.         //create new pianokey with specified pitch (from an array of pitches or whatever)
  35.         pianoKeys[i] = new PianoKey(pitches[i]);
  36.        
  37.         //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.
  38.         //the prefab would have the audiosource already, and you could set up the references to the audiosource in the inspector
  39.         //then you'd instantiate it like this
  40.        
  41.         GameObject newPianoKey = Instantiate(pianoKeyPrefab, Vector3.zero, Quaternion.identity) as GameObject;
  42.         pianoKeyScripts[i] = newPianoKey.GetComponent<PianoKey>();
  43.        
  44.         //and since the array is an array of the monobehavior, you could do stuff like
  45.         pianoKeyScripts[i].audio.Play();
  46.         pianoKeyScripts[i].isPressed = true;
  47.                
  48.     }
  49. }
  50.  
  51. void Update()
  52. {
  53.     for(int i = 0; i < pianoKeys.Length; i++)
  54.     {
  55.         if(pianoKeys[i].isPressed)
  56.         {
  57.             //play audio source if already not playing
  58.             if(!pianoKeys[i].audioSource.isPlaying)
  59.                 pianoKeys[i].audioSource.Play();
  60.         }
  61.         else
  62.         {
  63.             //stop audio source if playing
  64.             if(pianoKeys[i].audioSource.isPlaying)
  65.                 pianoKeys[i].audioSource.Stop();
  66.         }
  67.    
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement