- Home /
How do I make the enemy script/AI stop following me when It is in view of the player camera?
Hi! I'm pretty new to unity and C#. I've currently been making my game for about 2 weeks now and I'm stuck with the enemy script where it needs to stop when I look at it. Here is what I've done so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MoveEnemy : MonoBehaviour
{
public Transform Player;
int MoveSpeed = 6;
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 (GetComponent<Renderer>().isVisible)
{
MoveSpeed = 0;
}
if (!GetComponent<Renderer>().isVisible)
{
MoveSpeed = 6;
}
}
}
}
Even though I am no longer looking at it it still moves and I'm stuck here. if (!GetComponent().isVisible) Does not seem to work. I've also read multiple old posts about this that don't work anymore. Any tips?
Answer by Bentley · May 25, 2020 at 05:45 AM
See this post about the same problem. The solution by the user duck is more technical, but the answer by runevision works in a pinch. One of the provided answers also has a code snippet that you can copy (one of the solutions suggested by duck).
That's kinda weird, I found out how to make it work, the enemy model does not move if I have the scene renderer open but when I toggle "full screen on play" the enemy model moves. Thanks!
Your answer
Follow this Question
Related Questions
Help me with this code proplem,,Almost finish my game please help this once 3 Answers
Why when using get; set; in one script i'm getting null in other script that use it ? 1 Answer
Script executing through walls 1 Answer
c# - List with multiple types - Trading Engine - Stock Simulator 2 Answers
How can i create array of texture2d with variables names ? 2 Answers