簡體   English   中英

如何在 Unity 中切換角色?

[英]How can i switch between characters in Unity?

我正在開發一款游戲,您將在游戲中控制 2 個不同的角色。 所以我用他們自己的 (fps) 相機創建了 2 個角色並將它們制作成預制件。 我如何在這些字符之間切換?

我做了這樣的事情,它使我能夠從我想要的字符開始,並在我按 Tab 時切換到另一個字符。 但是當我在第二個播放器中按 Tab 時它不會消失,我觀察到索引並且它總是 0 為什么它在這里沒有改變?

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);
}

您可能應該獲取玩家狀態(位置、旋轉等),銷毀舊玩家,實例化新玩家並像這樣設置玩家狀態:

GameObject _currentPlayer;

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

你是什​​么意思“用自己的相機”? 相機是玩家預制的孩子嗎? 這聽起來不太好,並且在您創建新播放器時可能會導致一些問題。 您應該為相機編寫簡單的腳本以跟隨播放器或使用 Cinemachine imho

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM