Reputation: 1121
I'm trying to create a targeting system.
When I click on a skeleton enemy I want to be able to access the health and damage from the skeleton script and likewise, when I click on a different enemy, I want to get their specific health and damage.
The only way I can think of doing this is using the GetComponent
method, but is there a way to use a generic GetComponent
that uses a variable depending on what enemy I have targeted so I can get the data of a selected enemy based on that variable?
Upvotes: 2
Views: 2927
Reputation: 2451
You do not show any example code, so it's hard to see what you have and have not worked out, but this is one way of approaching the problem.
//Pseudocode
GameObject enemy = GetEnemy(); //This could be a raycast, collision or some other method.
Health enemyHealth = enemy.GetComponent<Health>();
It's really quite simple. Another approach might to be to send a message, and let the enemy handle it if appropriate. From the docs:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void ApplyDamage(float damage) {
print(damage);
}
void Example() {
gameObject.SendMessage("ApplyDamage", 5.0F);
}
}
From the sounds of it the problem you're having isn't getting the other component, but that you're mixing a bunch of unrelated functionalities together. An enemy gameobject
should generally speaking* have the same health component
as the main player. Health code should not be in the Enemy
and the Player
and the Destructible Box
components otherwise not only are you writing the same code many times over, you have difficulties interacting with the different implementations of the same thing.
* In advanced situations, the may be a valid need to have multiple implementations of a health script instead of a single huge class. In these situations some sort of abstraction is useful - e.g. interface, inheritance or message passing.
Upvotes: 4