Question by
CutterTheCoder · Dec 22, 2015 at 06:13 AM ·
errorreferencing
NullReferenceException: Object reference not set to an instance of an Object
I have a hand attack, when the enemy is in the hand collider i will deal damage to the enemy, then want to check which way i am facing taking the boolean from another script on the same object, I try reference the component in the awake function, but when i attack the enemy and it gets to the if statement it says the error about the condition 'playerMovement.facingRight'
Any Advice?
public class handAttack : MonoBehaviour {
public int damage = 20;
public float timeBetweenAttacks = 0.50f;
Rigidbody2D enemyRB;
PlayerMovement playerMovement;
float timer;
// Use this for initialization
void Awake ()
{
playerMovement = GetComponent<PlayerMovement>();
}
// Update is called once per frame
void Update ()
{
timer += Time.deltaTime;
}
void ResetAttack()
{
timer = 0f;
}
void OnTriggerStay2D (Collider2D other)
{
if (Input.GetButton("Fire1") && timer >= timeBetweenAttacks && other.gameObject.CompareTag("Enemy"))
{
EnemyHealth enemyHealth = other.gameObject.GetComponent<EnemyHealth>();
enemyRB = other.gameObject.GetComponent<Rigidbody2D>();
ResetAttack(); //Allows a 'rate of fire'
enemyHealth.TakeDamage(damage);
if(playerMovement.facingRight == true)
{
enemyRB.AddForce(new Vector2(10f, 0f));
}
if (playerMovement.facingRight == false)
{
enemyRB.AddForce(new Vector2(-10f, 0f));
}
}
}
}
Comment
After line 37 Debug.Log(enemyRB.name);
Also using Input inside OnTriggers is a bad idea.
Answer by CutterTheCoder · Dec 22, 2015 at 07:39 PM
Found the problem, the problem was i was referencing the script that was attached to the gameObject when the script for attacking was attatched to the child(hand)