- Home /
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
Liyzan.Init("Liyzan",300000,200,true);
print (string.Format("{0}",Liyzan.Name));
//LiyzanPlayerAi.AiInit(Liyzan);
/**********************************/
}
// 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
I dont know what "no problem" means. You mean if you call GetComponent
I dont know what wrong with my comment. Just typed it 5 6 times and missed so much characters. Anyway @jbarba_ballytech 's answer is what you need.
Answer by hoy_smallfry · Jul 31, 2013 at 08:30 PM
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:
[RequireComponent(typeof(Country))]
public class TestAiPlayer : NormalAi
{
...
}
This makes sure that when you add TestAiPlayer
, it attaches Country
to the GameObject
right before it attaches TestAiPlayer
.
2) You can also use the ??
operator, like so:
Liyzan = GetComponent<Country>() ?? AddComponent<Country>();
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>();
}
Jbarba, thank you so much for the advice. I never though of using a Attribute(I never use attributes, still hard headed about those because of starting with plain old C). I'll definitely start giving
attributes more thought in my code design. Thanks again.