以下是本期节目的屏幕录制:https://youtu.be/WnFuhhiBS7M
有2个玩家。每个人身上都有玩家脚本。那个脚本负责跳跃功能。
现在当我玩这个游戏并按下跳跃按钮时,两个玩家都按预期的那样跳跃。
当我关闭其中一个玩家的脚本,然后按下跳转按钮,仍然两个玩家都跳转。这怎么可能?
我使用以下代码在层次结构中“查找”按钮,并将跳转函数分配给按钮:
查找按钮
private void Start() {
characterColliderTrigger = transform.GetComponentInChildren<BoxCollider2D>();
characterCollider = transform.GetComponent<BoxCollider2D>();
GameObject[] movementButtons = GameObject.FindGameObjectsWithTag("MovementButtons");
foreach (GameObject buttonObject in movementButtons)
{
Button button = buttonObject.GetComponent<Button>();
if (button != null)
{
if (button.name == "MoveLeftButton")
{
MoveLeftButton = button;
}
else if (button.name == "MoveRightButton")
{
MoveRightButton = button;
}
else if (button.name == "JumpButton")
{
JumpButton = button;
}
}
}
StartCoroutine(AssignButtons());
}
分配按钮
IEnumerator AssignButtons()
{
yield return new WaitForSeconds(0.5f);
//JUMP BUTTON
EventTrigger jumpEventTrigger = JumpButton.gameObject.AddComponent<EventTrigger>();
EventTrigger.Entry jumpPointerDown = new EventTrigger.Entry();
jumpPointerDown.eventID = EventTriggerType.PointerDown;
jumpPointerDown.callback.AddListener((data) => { Jump(); });
jumpEventTrigger.triggers.Add(jumpPointerDown);
}
跳转功能
public void Jump()
{
if(canJump && !someoneOnTop)
{
rb.velocity = new Vector2(rb.velocity.x,25);
canJump = false;
}
}
1条答案
按热度按时间31moq8wy1#
这是因为你给按钮分配了一个回调函数。你至少有两种方法来纠正这个问题:
void OnEnable()
中,并取消分配void OnDisable()
方法上的回调。Jump()
方法是否启用了脚本,在您的情况下,只需在您的条件下添加this.enabled
。