我希望每当我的玩家通过障碍物的特定部分时,它的得分就会增加 2 分。为了做到这一点,我创建了障碍物的 child 。该子项包含覆盖障碍物特定部分的盒子碰撞器(我已在 Unity 中打开 Is Trigger)。
关于具有触发器的子级的代码 -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Score : MonoBehaviour
{
float points;
void Start()
{
}
void Update()
{
Debug.Log(points);
}
void OnTriggerExit2D(Collider2D other)
{
points += 2f;
}
}
问题是在控制台中点仅显示 0 和 2,如下所示 -
虽然经过障碍物后应该是0、2、4、6...。
还会创建原始障碍物的克隆,即我每次都会经过一个新的克隆;万一这导致了问题。
最佳答案
是的,很明显它会打印出 0 和 2,因为您的脚本不使用集中式评分系统,它只是更新该特定实例中的分数。您可以创建另一个名为 GameManager 的脚本,您可以在其中创建玩家分数变量,并且在子函数的触发器退出函数上会增加该 GameManager 变量玩家分数的分数。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public float playerPoints = 0f;
}
在乐谱脚本中
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Score : MonoBehaviour
{
public GameManager manager; // Drag and drop the gamemanager object from scene in to this field
void OnTriggerExit2D(Collider2D other)
{
manager.playerPoints += 2f;
Debug.Log(manager.playerPoints);
}
}
关于c# - 在 Unity 中使用触发器得分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72111674/