Why Doesn't Getcomponent add script to game objects inspector automaticly?

Hello guys, right now I’m playing around with unity and have read up alot on GetComponent. I have a Script that inherits from another custom script. The problem is using .getcomponent doesn’t add the needed script to the game object automaticly. So I find my self having to use to add it manual. Is there just a normal limitation of unity with C#? While Reading Forums people using Java have no problem using .GetComponent<>

using UnityEngine;
using System.Collections;

public class TestAiPlayer : NormalAi
	Country Liyzan;
	NormalAi LiyzanPlayerAi;

	// Use this for initialization
	void Start ()
		Liyzan = GetComponent<Country>();//works just fine if Country.cs is placed manually
		LiyzanPlayerAi = GameObject.Find ("PlayerAI").GetComponent<NormalAi>();//works just fine if NormalAi.cs is placed manually
		print (string.Format("{0}",Liyzan.Name));
	// Update is called once per frame
	void Update ()

Sure I can use .AddComponent(); but I just want to know if this is necessary or am I not using this method correctly. Thanks for the Help Guys

It doesn’t add it because it is not meant to add it, only get it; hence the name. You can remedy the situation one of two ways:

  1. If a script is dependent on another component (in this case, dependent on another script), you can use the RequireComponent attribute like so:

    public class TestAiPlayer : NormalAi


This makes sure that when you add TestAiPlayer, it attaches Country to the GameObject right before it attaches TestAiPlayer.

  1. You can also use the ?? operator, like so:

    Liyzan = GetComponent() ?? AddComponent();

This operator checks the value on the left side of the ??. If it is not null, it uses the value on the left side, and if it is null, it uses the right side instead.

The ?? operator is basically shorthand for this:

Liyzan = GetComponent<Country>();
if(Liyzan == null)
    Liyzan = AddComponent<Country>();