Home > Back-end >  How can i switch between characters in Unity?
How can i switch between characters in Unity?

Time:06-25

I was working on a game which you will control 2 different characters during the game. So I created 2 character with their own (fps)cameras and made them prefabs. How can i switch between these characters?

CodePudding user response:

I made something like this it makes me able to start with character that I want and switchs to another when I press tab. But it does not go when I press tab in the second player, I observed index and it is always 0 why it does not change here?

public GameObject[] players;
[SerializeField] GameObject currentCharacter;

int index=0;

// players[0] is the player, players[1] is the dark energy ghost.
void Awake()
{
    players[0].SetActive(false);
    players[1].SetActive(false);
}

void Start() // disables the 
{
    players[index].SetActive(true);
}

// Update is called once per frame
void Update()
{
    print(index);
    if(Input.GetKeyDown(KeyCode.Tab))
        ChangeCharacter(index);
    
}

void ChangeCharacter(int index){ // index keeps the current player
    
    players[index].SetActive(false);
    if(index == 0)
        index = 1;
    else
        index = 0;  
    
    players[index].SetActive(true);
}

CodePudding user response:

You should probably get player state (position, rotation etc.), destroy old player, instantiate new one and set player state like that:

GameObject _currentPlayer;

void ChangePlayer(GameObject playerPrefab){
    var playerPosition = _currentPlayer.transform.position;
    var playerRotation = _currentPlayer.transform.rotation;    
    Destroy(_currentPlayer);
    _currentPlayer = Instantiate(playerPrefab, playerPosition, playerRotation);
}

What do you mean "with their own cameras"? Camera is child of a player prefab? That does not sound good and may cause some problems when you create new player. You should write simple script for camera to follow player or use Cinemachine imho

  • Related