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 using get component. you have declare same component type which you pass in GetComponent method. 
  • now you can perform all operations on my_image and this will change image_object because it referencing it.

Accessing multiple component of same type

if a gameObject have multiple component of different type then we can reference to then declare each type and calling GetCompnent method but if same gameObject have same type of multiple component then for referencing them we can use GetComponents method
  • if a gameObject a many AudioSource attached to it then we declare a array of type AudioSource and then we will reference all audioSource by calling GetComponents method

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour
{
    public GameObject audio_object;
    private AudioSource[] my_audio;

    void Start()
    {
       my_audio = audio_object.GetComponents<AudioSource>();
    }
}


  • my_audio = audio_object.GetComponents<AudioSource>();  assign all audio one by one in it means my_audio[0] will reference to very first then my_audio[1] to second one just below of first and so on.
  • and then you can perform all operations on array my_audio.  




Popular posts from this blog

How to fix Android Gradle Build failed error in unity

Changing position of gameObjects in unity by C# script

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

Unity ads install error from package manager

SerializeField and HideInInspector in unity in C# script

playing audio in unity by C# script

how to setup unity ads in mobile game

Variables in C# script in unity

Activating and deactivating gameObjects in unity by C# script