Change NavMeshAgent Object ref in Script

Ok so with my current project my objective is to switch the character I’m controlling by clicking on them. The movement is like a moba/rts, I click on the character with left mouse, and right click somewhere to move them. I can already move one character fine, but switching is the part im struggling with. I’m using an empty object EventSystem with a script to control the objects. I know I should probably attach individual scripts to each character but I want to try doing it all from one script to learn referencing. I created the following game objects :

    public GameObject GOplayer; //Main object
    public NavMeshAgent Player; //The objects navmeshagent component

Then I created a function to handle switching characters:

    void ChooseCharacter()
    {
     
        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "Character") //If my click raycast hits the object with the tag "Character"
                {
                   
                    GOplayer = hit.transform.gameObject; //Change the GOplayer object reference to the one i clicked.
                    Player = GOplayer.GetComponent<NavMeshAgent>; //Change navmesh ref for future movement commands. ERROR
                    print(GOplayer.name); //Print the current selected objects name to make sure I did switch. Works.
                   
                }
            }
        }


    }

Now I know the Player = GOplayer.GetComponent thing doesnt work, but I cannot find the proper way to do it for the life of me. I just want that new objects navmesh into that variable(object?) so that it will carry out the commands of the playermovement() function instead of the object I dragged and dropped into these objects(variables?) from the unity editor.

please, no “Let me google that for you” links, I really tried. If there is a better resource for specific things like this please share if you dont want to answer directly here. I want to learn the theory behind this. I understand NavMeshAgent is a Type, and that you use Types to create Objects and also that my usage of it with GetComponent is incorrect but thats about it. Also not sure if creating that editor drag and drop object reference thing with “Type Name” (GameObject GOplayer) is called a variable or an object so sorry for any confusion.

It looks to me like you probably have a compile error on line 12 of your code snippet. You need an empty argument list at the end of the GetComponent call, like this:

Player = GOplayer.GetComponent<NavMeshAgent>();

Other than that, the code you shared looks ok.

1 Like

Thank you so much PraetorBlue!!! I was wracking my brain over something so simple, cant believe it! I dont know how to mark something as an answer here but yeah, thank you so much.

1 Like