我正在制作一個簡單的 2d 平臺游戲,我真的需要一些幫助。我有硬幣,玩家需要收集所有硬幣。我還有一把鑰匙和一扇門,玩家拿到鑰匙后門就會打開。問題是:鑰匙一直可見,但我希望在玩家收集所有硬幣后它才可見,這樣玩家就可以拿到鑰匙并結束這一章。我怎樣才能做到這一點?
這是我的玩家代碼:`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
private Rigidbody2D myRigidbody;
private Animator anim;
private int score;
public Text totalscore;
[SerializeField]
private GameObject playerhaskey, dooropened;
[SerializeField]
private int speed;
private bool lookright;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
score = 0;
lookright = true;
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
movements(horizontal);
changedirection(horizontal);
}
private void movements(float horizontal)
{
anim.SetFloat("Walk", Mathf.Abs(horizontal));
myRigidbody.velocity = new Vector2(horizontal * speed, myRigidbody.velocity.y);
}
private void changedirection(float horizontal)
{
if (horizontal > 0 && !lookright || horizontal < 0 && lookright)
{
lookright = !lookright;
Vector3 direction = transform.localScale;
direction.x *= -1;
transform.localScale = direction;
}
}
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.tag == "gold")
{
collider.gameObject.SetActive(false);
score = score 1;
changescore(score);
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "key")
{
other.gameObject.SetActive(false);
playerhaskey.SetActive(true);
dooropened.SetActive(true);
}
}
void changescore(int count)
{
totalscore.text = count.ToString();
}
}
`

uj5u.com熱心網友回復:
首先作為旁注,我將對鑰匙和硬幣使用相同的技術。您可以同時擁有一個OnTriggerEnter2D手柄。
然后我假設所有硬幣都在開始時啟用,并且顯然都有一個標簽gold,所以你可以簡單地做一些類似的事情
private int totalCoinsRequired;
private GameObject key;
private void Start()
{
// find the key object
key = GameObject.FindWithTag("key");
// find all coins -> amount needed to unlock key
totalCoinsRequired = GameObject.FindGameObjectsWithTag("gold").Length;
// initially hide the key
key.SetActive(false);
}
...
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.CompareTag("gold"))
{
collider.gameObject.SetActive(false);
score = 1;
changescore(score);
// if score reaches required amount unlock key
if(score >= totalCoinsRequired)
{
key.SetActive(true);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/525588.html
上一篇:更改Unity中手部跟蹤的增益
