Trying to impliment a 2D sidescroller enemeny follow player AI. Getting UnassignedReferenceException. Now idea how to fix, been lurking for days
Hello everyone. I'm currently learning Unity and I'm having trouble with this AI script. I get this error 50+ times a second while running my game.
I want the red robot to chase the grey robot.
Blockquote
UnassignedReferenceException: The variable Player of TestAI1 has not been assigned. You probably need to assign the Player variable of the TestAI1 script in the inspector. UnityEngine.Transform.get_position () (at C:/buildslave/unity/build/artifacts/generated/common/runtime/TransformBindings.gen.cs:27) TestAI1.Update () (at Assets/Scripts/TestAI1.cs:25)
Blockquote
and here is the code of my script in C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TestAI1 : MonoBehaviour
{
public Transform Player;
int MoveSpeed = 4;
int MaxDist = 10;
int MinDist = 5;
void Start()
{
}
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
//Call any function U want Like Shoot at here or something
}
}
}
}
If anyone can give me some insight that would be greatly appreciated!
this's not an answer to your question but a good tip for you...use Vector2.Distance ins$$anonymous$$d of Vector3.Distance for 2d games.
Answer by SuryaEU · Aug 25, 2017 at 05:57 PM
Hey, It might sound simple, but the error message looks pretty self explanatory:
You have the TestAI script on the robot chasing. You need to define what you are chasing (the "Player" object)
Maybe you just forgot to specify your object "Player", in the Unity inspector, in the TestAI script which is on the chasing robot.
You should drag your player object from the tree in your scene, and drop it in the Robot>TestAI>Player placeholder.
If you want something more visual, I found this video on youtube: https://www.youtube.com/watch?v=TnJhhz120js It's a bit more complicated than you need (here the guy is explaining how to specify several objects at once) but it should be easier to understand than plain text :)
Answer by Geads · Aug 25, 2017 at 06:08 PM
That is exactly what happened. I'm sorry about that. Thank you so much for your help.
Your answer
Follow this Question
Related Questions
How do I move a prefab the same speed as my scrolling background? 0 Answers
Enemy jump in unity 2d 0 Answers
Problems disabling an AI and giving control to the Player 0 Answers
Need Help Moving an object using specfic paramets 0 Answers
Script to get Eye Material to move only seems to work in Inspector/Edit Mode 0 Answers