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.