- Home /
Help with AI script
I created a script where the object will spawn if it isn't looked at after a certain time it becomes hostile and chases the player.
{
private bool Attack;
private bool Spawned;
private Transform script; // Use this for initialization void Start () {
Spawned = false;
Attack = false; Starting1();
}
public void Starting1()
{
StartCoroutine(Wait());
}
public void Starting2()
{
GetComponent<Renderer>().enabled = true;
StartCoroutine(Spawn());
}
public void Seen()
{
if (Spawned == true && Attack == false && GetComponent<Renderer>().enabled == true)
{
Debug.Log("Seen");
Starting1();
}
}
public void Attacking()
{
if(Spawned == false && Attack == true)
{
GetComponent<Aifollow>().enabled = true;
Debug.Log("Attacking");
}
}
// Update is called once per frame
IEnumerator Spawn()
{
Spawned = true;
Attack = false;
yield return new WaitForSeconds(1);
Attack = true;
Spawned = false;
}
IEnumerator Wait()
{
GetComponent<Renderer>().enabled = false;
yield return new WaitForSeconds(3);
Starting2();
}
}
The problem with the script if that it works fine until The Spawn Corutine is enabled. The object shows after 1 second yet i don't get a log showing that it's "Seen" when i am looking at it and I don't get a log showing that its "attacking" either. Any way to fix this?
The function Seen() and Attacking() have not been called anywhere. They need to be called somewhere in order for the debug to run. I think you can try calling "Attacking" in Spawn function()
IEnumerator Spawn()
{
Spawned = true;
Attack = false;
yield return new WaitForSeconds(1);
Attack = true;
Spawned = false;
Attacking();
}
I called Attacking() and Seen() in the spawn function and only Attacking() works not Seen()
IEnumerator Spawn()
{
Seen();
Spawned = true;
Attack = false;
yield return new WaitForSeconds(1);
Attack = true;
Spawned = false;
Attacking();
}
Seen() doesn't work because Spawn = true and Attack = false have been called in the next line.
Also I think you need to write an algorithm to deter$$anonymous$$e when to call the Seen() method.
Your answer
![](https://koobas.hobune.stream/wayback/20220612160151im_/https://answers.unity.com/themes/thub/images/avi.jpg)