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.

[HideInInspector]

If you want to access variables in other classes then we declare them as public and public variables are visible in inspector for example

    public int num = 4;

then "num" variable is visible and its value is shown '4' in inspector and then you can change it from here. sometimes it is our desired behaviour but sometimes not.

if we attach this script to gameObject and we show it "num" in inspector with value '4' but if we change  public int num = 14;  in script and save then we show that "num" still have '4' in inspector it is not changed so this is sometime good or not depend on situation to overcome this situation or we don't want to show private variable in inspector then we can use [HideInInspector] attribute. for example

    [HideInInspector]
    public int num = 4;

variable declared after [HideIn Inspector] attribute is not visible in inspector window. so now "num" is not visible in inspector.


Common problem in use case

if we create a script and declare a public variable and initialize as 4 and then we attach it to a gameObject and now if we change value of this variable to anything like '24' and we run are scene we see that our script have taken value of this variable still '4' instead of '24' .
whenever we declare a public variable and attacked to gameObject its value is saved and now whatever we change in script is not going to change either if have used [HideInInspector] attribute or not.
To resolve this problem you should have to reset script component by clicking three dot and then reset.

Popular posts from this blog

Positioning GameObjects in unity editor

Creating count down timer in unity by c# script

Changing Image in unity by C# script