我正在用c# Unity制作游戏。我有这个问题,当在碰撞事件,一切都发生,但不改变bool变量的值。游戏是2D的,碰撞事件确实发生了,只是有一行布尔值不起作用。我试着公开它,看看它是否有哪怕一秒钟的变化,但它根本没有变化。等待的IEnumerators只是为了声音效果和何时闭上嘴巴,所以它们不起作用。下面是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SizeScaling : MonoBehaviour
{
public Camera mainCamera;
private Vector3 scale;
private AudioSource mergeSFX;
public GameObject openMouth;
public GameObject closedMouth;
public bool mouth = false;
void Start()
{
mergeSFX = mainCamera.GetComponent<AudioSource>();
scale = new Vector3(0.05f, 0.05f, 0);
}
void Update()
{
openMouth.SetActive(!mouth);
closedMouth.SetActive(mouth);
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Down")
{
Destroy(collision.gameObject);
mergeObject(1);
}
else if (collision.gameObject.tag == "Up")
{
Destroy(collision.gameObject);
mergeObject(3);
}
else if (collision.gameObject.tag == "Left")
{
Destroy(collision.gameObject);
mergeObject(0);
}
else if (collision.gameObject.tag == "Right")
{
Destroy(collision.gameObject);
mergeObject(2);
}
StartCoroutine(close());
mouth = false;
}
void mergeObject(int addDirection)
{
PlayerMover.direction[addDirection]++;
openMouth.transform.localScale += scale;
closedMouth.transform.localScale += scale;
mergeSFX.Play();
mouth = true; // Doesn't execute line
StartCoroutine(wait());
}
IEnumerator wait()
{
yield return new WaitForSeconds(2f);
}
IEnumerator close()
{
yield return new WaitForSeconds(1f);
}
}
实际上,执行了这行代码,但随后将其分配给false
。首先,mergeObject(...)
方法在if
语句执行时,碰撞后将变量赋值给true
。但是,在此之后,将此值赋给这些行的false
。
void OnCollisionEnter2D(Collision2D collision)
{
//after all if statements
StartCoroutine(close());
mouth = false;
}
你不清楚该如何处理这个变量,但是下面的代码应该可以解决你的问题。
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Down")
{
Destroy(collision.gameObject);
mergeObject(1);
}
else if (collision.gameObject.tag == "Up")
{
Destroy(collision.gameObject);
mergeObject(3);
}
else if (collision.gameObject.tag == "Left")
{
Destroy(collision.gameObject);
mergeObject(0);
}
else if (collision.gameObject.tag == "Right")
{
Destroy(collision.gameObject);
mergeObject(2);
} else {
mouth = false;
}
StartCoroutine(close());
}
我修复了它,只是移动了bool在IEnumerator中设置为false的地方,现在它可以工作了,不知道为什么,但它确实可以。
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Down")
{
Destroy(collision.gameObject);
mergeObject(1);
}
else if (collision.gameObject.tag == "Up")
{
Destroy(collision.gameObject);
mergeObject(3);
}
else if (collision.gameObject.tag == "Left")
{
Destroy(collision.gameObject);
mergeObject(0);
}
else if (collision.gameObject.tag == "Right")
{
Destroy(collision.gameObject);
mergeObject(2);
}
StartCoroutine(wait());
}
void mergeObject(int addDirection)
{
PlayerMover.direction[addDirection]++;
openMouth.transform.localScale += scale;
closedMouth.transform.localScale += scale;
mergeSFX.Play();
mouth = true;
}
IEnumerator wait()
{
yield return new WaitForSeconds(2f);
mouth = false;
}