I keep getting a NullReferenceException on line 17 (the first IF statement), but only when I use transform instead of destroy. I prefer using transform to move objects into an area where a different script destroys them so that OnTriggerExit will work for the objects in their vicinity. However, I’m getting this really strange behavior where if I use “Destroy(gameObject);” I won’t get an error at all, but if I use any version of the commented code on lines 19-21 OR 27-29 I get an error in my IF statement on line 17 (even when I only change the code in the lower IF statement.
The explicit error is:
NullReferenceException: Object reference not set to an instance of an object
Arrow.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Used/Arrow.cs:17)
Any help would be greatly appreciated, every component of this code seems to work fine in other scripts. I feel like I’m taking crazy pills.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Arrow : MonoBehaviour {
private float speed= 3;
void Update ()
{
transform.Translate(Vector3.right * speed * Time.deltaTime);
Debug.Log(transform.position);
}
void OnTriggerEnter(Collider other)
{
if (other.GetComponent<Tags>().hasTag("Wall") && other.CompareTag(this.tag))
{
//gameObject.transform.position = new Vector3(5f, -2f, 5f);
//this.transform.position = new Vector3(5f, -2f, 5f);
//transform.position = new Vector3(5f, -2f, 5f);
Destroy(gameObject);
}
if (!other.CompareTag(this.tag) && other.GetComponent<Unit_Health>() != null)
{
other.GetComponent<Unit_Health>().AdjustHealth(-1);
//gameObject.transform.position = new Vector3(5f, -2f, 5f);
//this.transform.position = new Vector3(5f, -2f, 5f);
//transform.position = new Vector3(5f, -2f, 5f);
Destroy(gameObject);
Debug.Log("Arrow attack");
}
}
}