- Home /
Can I access a script OnTrigger WITHOUT using getcomponent?
I am trying to optimize one of my scripts by removing getcomponent. Basically I have a trigger, and when certain objects enter it I am accessing that object's script (named "AICar_Script") via getcomponent and changing some variables.
At the moment everything is running fine, but since I have quite a few of these triggers and getcomponent is quite slow I am wondering if it is possible to access the script directly when the object enters the trigger (without using getcomponent each time). The documentation doesn't mention this. Here is the trigger part:
// Hit the brakes when the AI enters the trigger
function OnTriggerEnter (other : Collider) {
if (other.CompareTag ("FastAICar") || ("MediumAICar") || ("SlowAICar")) {
if (other.gameObject.GetComponent(AICar_Script)) {
other.gameObject.GetComponent(AICar_Script).Accelerate = false;
}
}
}
I have tried accessing these directly in this way, but I am getting errors on both lines:
// Hit the brakes when the AI enters the trigger
function OnTriggerEnter (other : Collider) {
if (other.CompareTag ("FastAICar") || ("MediumAICar") || ("SlowAICar")) {
if (other.gameObject.aICar_Script != null) {
other.gameObject.aICar_Script.Accelerate = false;
}
}
}
In the AICar_Script I have made a reference to itself so that it can be accessed publicly, and I see it getting assigned when I run the the game:
//Reference to this script so that other scripts can easily access it
var aICar_Script : AICar_Script;
function Start () {
aICar_Script = GetComponent("AICar_Script");
}
Am I doing something wrong, or do I simply have to use getcomponent each time when using OnTrigger(whatever)?
Answer by whydoidoit · May 14, 2013 at 06:32 AM
Well the most optimal way of doing your OnTriggerEnter is:
// Hit the brakes when the AI enters the trigger
function OnTriggerEnter (other : Collider) {
var carAI = other.GetComponent(AICar_Script);
if(carAI) carAI.Accelerate = false;
}
So no you should use GetComponent, but you should only use it once. And if you are using it like this ignore all of the tag stuff.
Thank you very much. Can't test this right now, but just of the top of my head, wouldn't that give me a null reference if something without a AICar_Script enters the trigger?
Also just to clarify, if I am using multiple objects that can potentially enter/exit/stay each trigger at the one time, should I use getcomponent only OnTriggerEnter (once), or in OnTriggerStay and Exit as well (three times)?
You should use it in each function - you have to, that function will be called for each object of which there may well be more than one.
Ok thanks a lot. I've tested the OnTriggerEnter and Exit so far and it is working well. Stay will take a little more work but I'm sure it'll be fine just the same. Thanks for your help