Posts

Showing posts with the label audio

GetComponent method in unity to access component by C# script

In many case you have to access component attached with a gameObject then change its properties and value so here is a simple method of doing this Create a C# script and open it first declare a gameObject whose component you want to access. Then declare a component type to reference component for example if you want to access Image component declare Image or want to access AudioSource declare AudioSource. now you can call gameObject.GetComponent<Type>() method for referencing. using   System . Collections ; using   System . Collections . Generic ; using   UnityEngine ; using   UnityEngine . UI ; public   class   test  :  MonoBehaviour {      public   GameObject  image_object;      private   Image  my_image;      void   Start ()     {         my_image  =  image_object . GetComponent < Image ...

playing audio in unity by C# script

Image
  Audio in unity are played with the help of AudioSource component and you can access it by script and control play, pause, and stop operations.  First create a empty gameObject and add AudioSource component in it. then drag and drop you music clip in it. AudioSource component have various other options you can customize according to you needs. It have loop option if it toggled on then our AudioClip will repeat again and again when finish. so if you want to play only once then you can turn off but if you want want to play continuously then turn on. It also have play on awake toggle default turn on. so turn it off if you don't want to play music as soon as game start. Create a C# script and create a other empty gameObject in inspector and drag and drop this script into gameObject. Now open script and declare a public GameObject of name "audio_object" for refencing gameObject have audioAource and an private AudioSource named "my_audio" for accessing AudioSource cc...