Search code examples
c#visual-studiounity-game-enginenavmesh

How to change conditions in Update() unity c#


I have created navMeshand agent. For target I used two empty object. For each empty object I created two buttons.

If I click on white button agent moves to empty target first again I click on red button agent moves to 2nd empty target.

I am facing problem when I want move agent from target-2 to target-1. How I can move that agent to taeget-1?

See video for better understanding

video link https://youtu.be/zRKHdMeQsi0

Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class SampleAgentScript : MonoBehaviour {

    public Transform target , target2;
    NavMeshAgent agent;
    private static bool start1=false , start2=false;

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
    }

    public static void buttonClick()
    {
        //if white button click
        start1 = true;
    }

    public static void buttonClick2()
    {
        //if red button click
        start2 = true;
    }

    void Update()
    {
        if (start1) //if white button click moves to targer-1
        {
            agent.SetDestination(target.position);
        }

        if (start2) //if red button click moves to targer-2
        {
            agent.SetDestination(target2.position);
        }
    }
}

Solution

  • May be this will help.

    public static void buttonClick()
    {
          //if white button click
        start1 = true;
        start2 = false;
    }
    
    public static void buttonClick2()
    {
         //if red button click
        start2 = true;
        start1 = false;
    }