I keep getting the NullReferenceException error. Now, I know that unity is telling me that I haven't set an instance of an object correctly but I can't work out what I am doing incorrectly. Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Wolf : Enemy
{
private Transform target;
private Transform home;
private StickPickup stickScript;
private bool hasReachedDestination = false;
private float hunger = 50f;
// Start is called before the first frame update
public override void Start()
{
base.Start();
target = sticks.transform;
home = GameObject.Find("Cave").transform;
}
// Update is called once per frame
void Update()
{
hunger -= Time.deltaTime;
if(hunger <= 40f)
{
GoHunting();
}
else
{
ReturnHome();
}
}
void GoHunting()
{
if(target != null)
{
if(Vector3.Distance(transform.position, target.position) > 0.1f)
{
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
hasReachedDestination = true;
GrabStick();
}
}
else
{
CalculateNextStick();
}
}
void CalculateNextStick()
{
Debug.Log("test", target);
target = GameObject.FindGameObjectWithTag("Sticks").transform;
stickScript = GameObject.FindGameObjectWithTag("Sticks").GetComponent<StickPickup>();
hasReachedDestination = false;
}
void GrabStick()
{
bool checkDistance = IsTouching();
if(checkDistance == true)
{
stickScript.DestroySelf();
hunger = 50f;
}
}
private bool IsTouching()
{
if(Vector3.Distance(transform.position, target.position) < 0.1f)
{
return true;
}
else
{
return false;
}
}
void ReturnHome()
{
transform.position = Vector3.MoveTowards(transform.position, new Vector3(-16f, 9.38f, 0f), speed * Time.deltaTime);
}
}
The problem line it's specifically picking up is this one here:
target = GameObject.FindGameObjectWithTag("Sticks").transform;
Also here is the base class that the Wolf inherets from:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField] protected float speed;
[SerializeField] protected bool isScared;
[SerializeField] protected Transform sticks;
// Start is called before the first frame update
public virtual void Start()
{
sticks = GameObject.FindGameObjectWithTag("Sticks").transform;
}
// Update is called once per frame
void Update()
{
}
}
I am not that great at OOP related programming but it looks like I am assigning it correctly. I am not really sure how to debug this one either. If you have any suggestions that would be awesome.