i saw in a course this script that makes enemy search MC its not finished yet
this just make the NPC walk around, i wnat to create a AI like skyrim where the npc go to places and do some action sitting, the question is this kind of scripts is
Is this the best way or is there a more practical and efficient way?
The best way is the one that works for you. This is engineering, so you are looking for a solution to your specific AI problems, which are intimately tied to your game and how you want it to work. Try some solutions, see if they work. If they don’t try other solutions, or meaningfully ask questions here, such as in the format of:
- I did this piece of code that is intended to do X
- I expected this behaviour
- but it actually did something else
Also, screenshots of code are not a thing.
If you post a code snippet, ALWAYS USE CODE TAGS:
How to use code tags: https://discussions.unity.com/t/481379
You can edit your post above.
That’s going to have problems in the update method. You’re starting a coroutine every frame once the agent reaches the destination. I’d recommend looking into Finite State Machines. It’s a big topic, so looking for Unity specific tutorials is best. If that’s too much of an ordeal at this point, then here’s a simple pattern you can use:
using System;
public class FSM_AI : MonoBehaviour
{
private Action currentState;
private void Start()
{
currentState = InitialState;
}
private void Update()
{
currentState?.Invoke();
}
private void InitialState()
{
if(Time.realtimeSinceStartup > 10)
{
currentState = WaitState;
}
}
private void WaitState()
{
// Do nothing
}
}
So, when changing states you assign a new method to currentState. Experienced programmers might yell at me for doing this, but it works pretty well as an introduction to how a state machine works. Essentially, each new method is a new “state” that your npc is in. When you want to move from waiting to chasing the player, you assign a chasing state. The main problem with the approach is that it doesn’t scale very well. When you’re ready for full glorious OOP SOLID state machines, then move on to those.
1 Like