Posts

Showing posts from September, 2021

Changing Image in unity by C# script

 There are two case when you want to change image one is UI image and other is a sprite in scene so in this post we will take a look at both cases how to change images. Changing UI Image There are very few steps to change UI image scripts First create a UI image gameObject in scene whose image we want to change create a script and attach with an other empty gameObject and open script In script declare a public GameObject for referencing changing image and a declare a private Image variable for refencing Image component in this gameObject also declare a public Sprite for which image that we want in replacement. using   System . Collections ; using   System . Collections . Generic ; using   UnityEngine ; using   UnityEngine . UI ; public   class   test  :  MonoBehaviour {      public   GameObject  image_object;      public   Sprite  mySprite;      private   Image  myImage;      void   Start ()     {          myImage  =  image_object . GetComponent < Image >();          myImage . sp

Finding a GameObject by C# script in unity

 There are main three ways of finding a gameObject in scene by script GameObject.Find() mehod You can pass string name in it and it will then search for that name in scene gameObject and return very first name which exactly match with it. using   System . Collections ; using   System . Collections . Generic ; using   UnityEngine ; public   class   test  :  MonoBehaviour {      private   GameObject  player;      // Start is called before the first frame update      void   Start ()     {          player  =  GameObject . Find ( "main_character" );          Debug . Log ( player );     } } In this example code we have declare a private GameObject and then we assign it by calling find() method. if there is exact same name gameObject in hierarchy then it assign and show name in debug message or otherwise show a null message. GameObject . Find ( "main_character" );   whatever string we pass in Find() method should be same means upper case, lower case or even spaces between

SerializeField and HideInInspector in unity in C# script

You can declare a variable as private or public according to you if you don't want to access variable outside of class then declare as private and want to access in other classes then declare public. Unity have two attribute for these variables lets take a look  [SerializeField]  Whenever you declare a private variable it is only accessible inside its class and variable can not be shown in inspector window in editor. So if you want to change value of this private variable you have to change inside script.      private   int  num =  5 ; this variable "num" will not show in inspector window.  If we want to show private variable in inspector window then we can use SerializeField attribute for example      [ SerializeField ]    private   int  num =  5 ; next declared variable after SerializeField attribute will be visible in inspector and we can change its value just by changing in inspector instead of script. Now "num" variable is visible in inspector window. [Hid

Activating and deactivating gameObjects in unity by C# script

Sometimes it is very useful to active or deactivate a gameObject by script. For this gameObject class have a called SetActive(). You can pass true or false in to active or deactivate For activating gameObject by script first declare a gameObject and then drag and drop in inspector or use Find method for referencing gameObject. then use gameObject.SetActive(true) when you want to visible (activate) gameObject.SetActive(false) when want to deactivate gameObject. if gameObject is parent object then its all child object will also deactivaate. using   System . Collections ; using   System . Collections . Generic ; using   UnityEngine ; public   class   test  :  MonoBehaviour {      public   GameObject  my_object;      // Start is called before the first frame update      void   Start ()     {            }      void   Update ()     {          if ( Input . GetKeyDown ( KeyCode . A ))         {              my_object . SetActive ( true ); //activate gameObject         }          if ( Input . G

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 >();     } } For accessing UI component we have added   using   UnityEngine . UI ;   namespaces. my_image  =  image_object . GetComponent < Image >();   this is basic syntax of usin

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

WaitForSeconds and coroutine in unity | delaying a code action for some time in C#

 If you want to delay a code for few seconds in C# then you can use coroutine in unity. There are two methods of doing this - WaitForSeconds() method For creating a delay you first need to create a function of IEnumerator type and you can call it inside StartCoroutine() method when you want delay. let's see an example code  using   UnityEngine ; public   class   test  :  MonoBehaviour {      void   Start ()     {         StartCoroutine ( Wait_Example ());     }      IEnumerator   Wait_Example ()     {          Debug . Log ( 0 );//run as soon as function run          yield   return   new   WaitForSeconds ( 4 );          Debug . Log ( "4" );// run after 4 seconds     } } In above example we have declare a function Wait_Example(). yield   return   new   WaitForSeconds ( 4 );  this code will pause code written after it.  Debug . Log ( "4" );  run after time passed written in WaitForSeconds() function. code written before WaitForSeconds() execute as soon as function

Changing position of gameObjects in unity by C# script

Image
Unity have a class for holding and changing value of a gameObject that is transform, by this class you can change position, rotation, and size of a gameObject.  transform have three methods for changing position of a gameObject. Let's take a look at all three methods - 1. transform.Translate() Method First method that transform class have is transform.Translate(). This method is useful when you want to move your gameObject to particular position so this method directly move your gameObject to given position. using   System . Collections ; using   System . Collections . Generic ; using   UnityEngine ; public   class   test  :  MonoBehaviour {      // Start is called before the first frame update      void   Start ()     {         transform . Translate ( 1,1,1 );// change position to 1,1,1              } } By calling this method you have to enter x, y, and z coordinate in Translate method as seen above in code example  transform . Translate ( 1,1,1 );  . as soon as we run our scene i