How to call a function of a dynamically referenced gameObject?

I am fairly new to Unity and I’m making an RTS battle game where each troop has a trigger collider. When an enemy enters the trigger area, they are set as target and attacked. If anything else enters the trigger area once the target is still alive and being attacked, they are ignored. To make them take damage, I was going to get ‘other’ from the OnTriggerEnter function, and do
other.GameObject.SendMessage("takeDamage", attackDamage)
I discovered that messages are bad practice and realised I could just do
other.GameObject.GetComponent("TroopScript").takeDamage(attackDamage)
However, as ‘other’ is only determined once the script runs, this returns an error saying it does not contain a definition for takeDamage. I also could not figure out how to make the event system only apply for the troop’s single target rather than all enemies in range.
How would I actually make it so that just that troop takes damage? Are messages the only way?

The issue is you’re using the non-generic version of GetComponent there, which just returns the base type of Component.

Use the generic GetComponent<T> instead, so you get a strongly typed reference to your component. Though I would suggest to use TryGetComponent<T>(out T) instead for that sort of component look-up.

1 Like

Thank you that is very helpful, but what if I have two scripts on my game object, one for movement and one for fighting? How would I only get the fighting one?

… that’s what Get/TryGetComponent<T> does. If you only want the fighting one, put that type in T, and you’ll get the component of that type, ignoring the other ones.

Ah I see thank you