I am a little stuck. Basically I have a bunch of enemies each sharing the same hitScript. I want to affect one of them when I collide. However I don’t want to get the Component each time I hit the object.
Right? So how can I preload the hitScript while still knowing which hitObject I am attacking?
Does this makes sense?
Any help is appreciated…
if(hit.collider.tag == "hit" ){
var hitObject = hit.collider;
var hitScript : HitScript = hitObject.GetComponent("HitScript") as Component;
hitScript.gotHit(hit.point);
};
You can’t, because you wouldn’t be caching “every hit script”- you could only cache an instance of the hit script, which is different for every object. So there’s no way (conceptually, or otherwise) to get around doing a GetComponent call when you receive a hit.
If you’re worried about efficiency, your heart is in the right place, but you don’t need to go quite that far - the raycast you’re using, for example, probably takes dozens if not hundreds of times as long to calculate as a single GetComponent call. You could, however, improve the efficiency of the call by passing the class name rather than a string, and the “as Component” is redundant:
var hitScript : HitScript = hitObject.GetComponent(HitScript);