SerializeField and public
- Game Development course
- Beginner
- Lesson 35/83
- 4 min
Learn to use SerializeField and public for Inspector-visible fields.
Public fields
Fields declared as public appear in the Inspector window and can be edited there. This way you can change the value without touching the code.
public class Dusman : MonoBehaviour
{
public int can = 100;
public float hiz = 5f;
}These fields are reachable both from code and from the Inspector.
[SerializeField]
private fields are not visible in the Inspector by default. When you add the [SerializeField] attribute, the field stays private but becomes visible in the Inspector.
public class Dusman : MonoBehaviour
{
[SerializeField] private float hiz = 5f;
}This way the value can be set from the Inspector while the field stays hidden in code.
Practice Inspector fields
In a class named Dusman, declare a public int can = 100; field. Then make a private float hiz field visible in the Inspector with [SerializeField], and in Start print "Hazir" with Debug.Log.
Starter code
using UnityEngine;
public class Dusman : MonoBehaviour
{
// 1) can adli public tamsayi alani ekle (degeri 100)
// 2) hiz adli private ondalik alani Inspector'da gorunur yap
// 3) Start icinde "Hazir" metnini yazdir
}Sample solution
using UnityEngine;
public class Dusman : MonoBehaviour
{
public int can = 100;
[SerializeField] private float hiz = 5f;
void Start()
{
Debug.Log("Hazir");
}
}Expected output
Hazir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens to a field declared as public in a class?
- It appears in the Inspector and its value can be edited there Correct answer
- It causes a compile error
- It automatically becomes static
- It is reachable only from code and does not appear in the Inspector
Explanation: Public fields are visible in the Inspector and can be edited through it.
2 Expose a private field to the Inspector
____
private float hiz = 5f;
[SerializeField]
private float hiz = 5f;
Explanation: The [SerializeField] attribute makes a private field appear in the Inspector.
3 Inspector fields
| Term | Meaning |
|---|---|
public |
Makes the field visible in the Inspector |
[SerializeField] |
Shows a private field in the Inspector |
Inspector penceresi |
Where you edit the values of fields |
private |
Not visible in the Inspector by default |