- Home /
CSharp Script Error NullReferenceException
This is the error : NullReferenceException: Object reference not set to an instance of an object EnemyAttack.Attack () (at Assets/SCRIPT/EnemyAttack.cs:44) EnemyAttack.Update () (at Assets/SCRIPT/EnemyAttack.cs:34)
This is my code : using UnityEngine; using System.Collections;
public class EnemyAttack : MonoBehaviour {
public float maxDistance;
public float coolDownTimer;
public PlayerHealth ph;
private Transform myTransform;
public Transform target;
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag ("Player");
target = go.transform;
myTransform = go.transform;
maxDistance = 3;
coolDownTimer = 0;
ph = (PlayerHealth)go.GetComponent (typeof(PlayerHealth));
}
// Update is called once per frame
void Update () {
float distance = Vector3.Distance (target.position, myTransform.position);
if (distance < maxDistance) {
Attack ();
}
if (coolDownTimer > 0) {
coolDownTimer = coolDownTimer * Time.deltaTime;
}
if (coolDownTimer < 0) {
coolDownTimer = 0;
}
}
void Attack () {
if (coolDownTimer == 0) {
ph.ChangeHealth (-10);
coolDownTimer = 1;
}
}
}
your variables target
and myTransform
are initialized with same value go.transform
so how would go
calculate a distance from itself
Answer by tanoshimi · May 17, 2016 at 05:45 AM
Your line numbering is screwy, but I'don't guess the line causing the error is:
ph.ChangeHealth (-10);
Given the only object reference on that line is ph
, that rather suggests that you haven't assigned it, which means this line must have failed:
ph = (ph)go.GetComponent (typeof(PlayerHealth));
Are you sure you have only a single object in your scene tagged "Player", and that object definitely has a Player Health component attached?
Your answer
Follow this Question
Related Questions
Attaching objects to objects In game 0 Answers
How do I check if the gameobject I collided with has a certain script? (C#) 1 Answer
Problem with saving List of objects !!! 2 Answers
System.InvalidOperationException: Cannot start process because a file name has not been provided 0 Answers
How can I fix this error in my Candy Crush style game? 0 Answers