Quantcast
Viewing all articles
Browse latest Browse all 2891

What is wrong with my code

I'm making a script that allows the player to fire bullets at an enemy but when I finished making it I got this error: NullReferenceException: Object reference not set to an instance of an object Playershooting.Attack () (at Assets/Scripts/Player Scripts/Playershooting.cs:40) Playershooting.Update () (at Assets/Scripts/Player Scripts/Playershooting.cs:27) Here are my scripts being used: using UnityEngine; using System; [RequireComponent(typeof(AudioSource))] public class Playershooting : MonoBehaviour { public Vector3 bulletOffset = new Vector3 (0, 0.5f, 0); public float attackDelay = 0.5f; public int attackDamage = 10; public GameObject playerBullet; GameObject enemy; DamageHandlerEnemy damageHandlerEnemy; AudioSource shotSound; float timer; void Awake () { enemy = GameObject.FindGameObjectWithTag ("Enemy"); damageHandlerEnemy = enemy.GetComponent (); shotSound = GetComponent (); } void Update () { timer += Time.deltaTime; if (timer >= attackDelay) { Attack (); } } void Attack () { Vector3 offset = transform.rotation * new Vector3 (0, 0.5f, 0); if (Input.GetButton("Fire1")) { timer = 0f; shotSound.Play (); Instantiate (playerBullet, transform.position + offset, transform.rotation); } if(damageHandlerEnemy.currentEnemyHealth > 0) { damageHandlerEnemy.enemyDamaged (attackDamage); } } } using UnityEngine; using System.Collections; public class DamageHandlerEnemy : MonoBehaviour { public int startEnemyHealth = 10; public int currentEnemyHealth; bool isdamaged; bool isDead; void Awake () { currentEnemyHealth = startEnemyHealth; } void Update () { } public void enemyDamaged(int amount) { isdamaged = true; currentEnemyHealth -= amount; if (currentEnemyHealth <= 0 && !isDead) { Death (); } } void Death() { isDead = true; Destroy (gameObject); } }

Viewing all articles
Browse latest Browse all 2891

Trending Articles