Im new in unity and im tryin to get familiar to mading scripts so im making a simple scene where the player needs to kill the enemy but in the attack script i get this error: NullReferenceException: Object reference not set to an instance of an object
Target1.attack () (at Assets/Target1.cs:66)
Target1.Update () (at Assets/Target1.cs:37) and i have a problem that when i attack the enemyhealth dont get affected
please help me to find whats happening
here are the scripts
Attack
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Target1 : MonoBehaviour {
public Transform selectedTarget;
public Transform enemy;
public bool Enemy = false;
public Transform myTransform;
public Rigidbody Bala;
public Transform placementspot;
private EnemyHealth enemyHealth;
void awake (){
enemyHealth = GetComponent <EnemyHealth>();
}
void Update(){
if (Input.GetMouseButtonDown(0)){ // when button clicked...
RaycastHit hit; // cast a ray from mouse pointer:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// if enemy hit...
if (Physics.Raycast(ray, out hit) && hit.transform.CompareTag("Enemy")){
DeselectTarget(); // deselect previous target (if any)...
selectedTarget = hit.transform; // set the new one...
SelectTarget(); // and select it
Debug.Log(hit.collider.name);
}
}
if (Enemy == true && Input.GetKeyUp(KeyCode.A)){//attack the enemy
Rotate();
Debug.Log ("it hits!");
attack();
}
}
private void SelectTarget(){
enemy = selectedTarget.transform;
Enemy = true;
}
private void DeselectTarget(){
Enemy = false;
}
private void Rotate (){
myTransform.LookAt (enemy.transform);
}
private void attack (){
Rigidbody clone;//instantiate the bullet
clone = Instantiate(Bala, placementspot.position, transform.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection(Vector3.forward * 10);
EnemyHealth eh = enemyHealth;//addjust the enemy health
eh.AddjustEnemyHealth(-10);
}
}
enemy Health
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour {
public int enemyHealth = 100;
public int enemyMaxHealth = 100;
private float healthBarLength;
// Use this for initialization
void Start () {
healthBarLength = Screen.width / 4;
}
// Update is called once per frame
void Update () {
AddjustEnemyHealth(0);
}
void OnGUI() {
GUI.Box(new Rect(10, 10, healthBarLength,20), enemyHealth + "/" + enemyMaxHealth);
}
public void AddjustEnemyHealth(int adj) {
enemyHealth += adj;
if(enemyHealth < 0)
enemyHealth = 0;
if(enemyHealth > enemyMaxHealth)
enemyHealth = enemyMaxHealth;
if(enemyMaxHealth < 1)
enemyMaxHealth = 1;
}
}