Hi, I am reading a Unity Book (Unity Games by Tutorials), which walks you through creating an alien shooting game. I am getting a console error saying UnassignedReferenceException : The variable target of Alien has not been assigned. How can I fix this?
Thank you.
Here is my Alien script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Alien : MonoBehaviour {
public Transform target;
private NavMeshAgent agent;
// Use this for initialization
void Start () {
agent = GetComponent();
}
// Update is called once per frame
void Update () {
agent.destination = target.position;
if (target !=null) {
agent.destination = target.position;
}
}
}
Your tutorial should cover it. You need to assign something to target. Chances are since the variable is public, they are doing a drag and drop in the inspector, but, that may not be the case as this is an Alien script, which means if you are instantiating the aliens, they will have to get their target from elsewhere.
So, you need to see how they are assigning a value to the target variable.
T̶h̶a̶t̶ ̶c̶o̶d̶e̶ ̶h̶a̶s̶ ̶n̶o̶ ̶A̶l̶i̶e̶n̶ ̶v̶a̶r̶i̶a̶b̶l̶e̶ ̶i̶n̶ ̶i̶t̶,̶ ̶s̶o̶ ̶t̶h̶a̶t̶ ̶c̶a̶n̶’̶t̶ ̶b̶e̶ ̶t̶h̶e̶ ̶s̶o̶u̶r̶c̶e̶ ̶o̶f̶ ̶t̶h̶e̶ ̶p̶r̶o̶b̶l̶e̶m̶.̶ I̶’̶m̶ ̶g̶u̶e̶s̶s̶i̶n̶g̶ ̶t̶h̶a̶t̶ ̶a̶n̶o̶t̶h̶e̶r̶ ̶s̶c̶r̶i̶p̶t̶ ̶i̶s̶ ̶t̶r̶y̶i̶n̶g̶ ̶t̶o̶ ̶u̶s̶e̶ ̶t̶h̶e̶ ̶A̶l̶i̶e̶n̶ ̶c̶l̶a̶s̶s̶,̶ ̶b̶u̶t̶ ̶i̶t̶ ̶i̶s̶n̶’̶t̶ ̶r̶e̶f̶e̶r̶e̶n̶c̶e̶d̶.̶
Make sure you’ve referenced “target”; probably you forgot to drag an object into its slot in the Inspector. If your target is instantiated, you’ll need to reference it via script (dragging a prefab into the target slot won’t work).
Follow your tutorial and make sure you haven’t skipped any steps!