I have this code and I don't know why hit.collider.gameObject.GetComponent("health")
is returning null
void Shoot() {
Vector2 mousePosition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
RaycastHit2D hit = Physics2D.Raycast (firePointPosition, mousePosition - firePointPosition, bulletRange, whatToHit);
if (Time.time >= timeToSpawnEffect) {
Effect ();
timeToSpawnEffect = Time.time + 1/effectSpawnRate;
}
if (hit.collider != null) {
if (hit.collider.name == "Enemy") {
Debug.Log(hit.collider.gameObject.GetComponent("health"));
}
//Debug.Log("We hit " + hit.collider.name + " and did " + damage + " damage");
}
}
Here is my enemy script
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour
{
public float health = 100f;
//... rest of the code
}
You need to get a reference to the script attached to the Enemy. Then use that script to manipulate the health.
Find the GameObject.
Get the reference to the script.
Manipulate the health.
In one line if you want to be badass.
Bonus tip:
health
should beprivate
andEnemyAI
should have a setter and a getter for that variable.You are using Unity are you not? It looks that way from the code you provided. GetComponent() is a method that returns a reference to a component of the game object. These are the things you drag onto a game object in the Editor. Things like Box-Colliders and Rigidbodys. The code you wrote will not return anything because there is no game component in Unity called "health". To get the health of the enemy,you need to set up a reference to the script controlling the enemy and get its health value from there.
However you would have to get the reference of the script that is attached to the GameObject. To do this you would need to use the following code.
Then in your shoot method you update the reference to the target.
The reaason I put an if() statement around it is so that you're not overloading the CPU with GetComponent requests if the target hasn't already changed.
From here you would simply change the value by using things such as