- Home /
GetComponent() vs Delegate/Event
For example I have 5 doors with the same Tween script to open and close, I also have 5 "Triggers" that controls a certain door and has a children "ChildTrigger" that knows that it has been switch(like in Portal 2) and then tells the parent trigger that it's been activated and the trigger parent will activate or control the door depends on how many children has been activated.
ParentScriptTrigger has variables like:
private int ChildTriggerCounter = 0; //When starting the game, this will increment on how many gameobject children does he has to be activated
public int ActivatedChildTrigger = 0; //Counter that will activate if it is equal to ChildTriggerCounter
private bool isActivated = false;
void Start()
{
foreach(Transform child in transform)
{
ChildTriggerCounter++;
}
}
void Update()
{
if(ChildTriggerCounter == ActivatedChildTrigger && !isActivated )
{
//Activate the door (Open or Move)
isActivated = true;
}
else if(ChildTriggerCounter < ActivatedChildTrigger && isActivated )
{
//Deactivate the door
isActivated = false;
}
}
and the Childtrigger script has:
private GameObject keyGO;
private ParentScriptTrigger parentScript;
void Start()
{
parentScript = transform.parent.GetComponent<ParentScriptTrigger >();
}
void OnTriggerEnter(Collider other)
{
if(other.tag == "Key" && !keyGO)
{
parentScript.ActivatedChildTrigger++;
keyGO = other.gameObject;
}
}
void OnTriggerExit(Collider other)
{
if(other.tag == "Key" && keyGO)
{
parentScript.ActivatedChildTrigger--;
keyGO = null;
}
}
Should I use a transform.parent.GetComponent() then increment a value of the parent's script or an event/delegate to the "ChildTrigger"?
Answer by Nicolaj Schweitz · Feb 17, 2014 at 11:03 AM
In this case, I I'd keep it simple and make a public variable and simply assign it in the editor and get on with it. At some point, when the size of the project calls for it, I'd reevaluate the implementation.
The risk when using the in-editor-assigned variable, is that the project might be garbled at some point and then you'll have to remember what was assigned to the variable on the monobehavior in the editor. To address that risk, you should go with either the GetComponent() or the delegate method.
Alternatively, you could use SendMessage, but that opens another can of worms, namely the performance can, which in this case, does not seem to be the issue. (Check out this answer for a note on performance between SendMessage, Delegates, and method calls)
Then, to answer your question: GetComponent vs Delegate?
In this particular case: Pick what you find easiest to maintain.