So I have a script that makes the player move, and It moves using velocity and It all works, its just when I right click it switches the players and the player that I was previously moving still moves for a little bit, is there any way to just full stop the player once i switch to the other player?
Heres the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private bool player1Using = true;
public GameObject player1;
public GameObject player2;
public float speed;
Rigidbody rb;
void EnableOtherPlayer()
{
player1.GetComponent<PlayerMovement>().enabled = player1Using;
player2.GetComponent<PlayerMovement>().enabled = !player1Using;
}
void Start()
{
EnableOtherPlayer();
rb = GetComponent<Rigidbody>();
}
void Update()
{
float xMove = Input.GetAxisRaw("Horizontal");
float zMove = Input.GetAxisRaw("Vertical");
rb.velocity = new Vector3(xMove * speed, rb.velocity.y, zMove * speed);
if(Input.GetMouseButtonDown(1))
{
player1Using = !player1Using;
EnableOtherPlayer();
}
}
}
I still cant fix the fact that, in my if statement, I want it to be that when I click a single time then it switches the player, but it only happens when i click twice, sometimes even three times
The Debug.Log(player1Using); that goes every frame works, and it says true every time until I click once, after I click once then it says false every two frames and it says true every two frames. Once I click twice then it says false every frame. And the EnableOtherPlayer(); doesnt do anything at all when I move it straight into the Update function. And the Debug.Log(); that is in the if statement never goes through. Also after I click once, then it moves both players at the same time.
By the way, I added the velocity removal if that changes anything. This is the script after I changed what u told me to change:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private bool player1Using = true;
public GameObject player1;
public GameObject player2;
public float speed;
Rigidbody rb;
void EnableOtherPlayer()
{
player1.GetComponent<PlayerMovement>().enabled = player1Using;
player2.GetComponent<PlayerMovement>().enabled = !player1Using;
}
void Start()
{
EnableOtherPlayer();
rb = GetComponent<Rigidbody>();
}
void Update()
{
float xMove = Input.GetAxisRaw("Horizontal");
float zMove = Input.GetAxisRaw("Vertical");
rb.velocity = new Vector3(xMove * speed, rb.velocity.y, zMove * speed);
if(Input.GetMouseButtonDown(0))
{
Debug.Log(name + ": clicked to:" + player1Using, gameObject);
rb.velocity = new Vector3(0, 0, 0);
player1Using = !player1Using;
}
Debug.Log(player1Using);
EnableOtherPlayer();
}
}
By the way, if it makes any difference. I am not using a button to click on or anything else to click on, I just tried to make it so when I click anywhere in the game it is supposed to switch players