【发布时间】:2018-12-16 10:28:27
【问题描述】:
编辑 - 经过测试,我发现只有一部电梯会动画。因此,如果我走进电梯,动画可能不会在其上播放,但会在另一部电梯上播放。我偶然注意到了这一点。我认为动画师会根据我接近的 OnTriggerEnter2D 来控制动画。显然,这导致了我遇到的错误。
如何正确标记电梯,以便只有我所在的电梯才会运行动画?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Elevator : MonoBehaviour
{
private GameObject door;
[SerializeField]
private Text uiTxt; // Elevator UI text element
[SerializeField]
private Image uiBg; // Elevator Background image
[SerializeField]
private Image uiFg; // Elevator Foreground image
private void Start()
{
door = GameObject.FindWithTag("Elevator");
door.GetComponent<Animator>().SetBool("doorOpen", false);// Starts closed has to be TRUE to open
door.GetComponent<Animator>().SetBool("doorClose", false); // Starts closed has to be TRUE to re-close
uiBg.enabled = false;
uiFg.enabled = false;
uiTxt.enabled = false;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
door.GetComponent<Animator>().SetBool("doorOpen", true);
door.GetComponent<Animator>().SetBool("doorClose", false);
uiBg.enabled = true;
uiFg.enabled = true;
uiTxt.enabled = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
door.GetComponent<Animator>().SetBool("doorOpen", false);
door.GetComponent<Animator>().SetBool("doorClose", true);
uiBg.enabled = false;
uiFg.enabled = false;
uiTxt.enabled = false;
}
else {
door.GetComponent<Animator>().SetBool("doorOpen", false);
door.GetComponent<Animator>().SetBool("doorClose", false);
}
}
}
我已将其设置为参数为布尔值的位置。当doorOpen 为真且doorClose 为假时,门打开。当 doorOpen 为 false 且 doorClose 为 true 时,它将关闭。但是,如果两个值都为 false,它将什么也不做。
注意 - 我使用的是 Unity 2019.1 Beta
【问题讨论】:
-
我很确定它会处理
door = GameObject.FindWithTag("Elevator");,因为这两个脚本可能得到相同的游戏对象... -
@Eddge 如何单独分离它们?
-
您可以将此脚本附加到电梯游戏对象本身,然后在该对象上调用 getComponent(您也可以给电梯触发器)或者您可以使用
[SerializeField]并将其附加到它们在检查器中。 -
门 = GetComponent
();这会将它们单独分开吗?或者我需要 door.GetComponent (); ? -
每个 Monobehavior 都已经引用了它的 GameObject,所以如果这个脚本已经附加到电梯上,那么完全删除你的
GameObject door并在开始时使用Animator myAnim = getComponent<Animator>();并执行所有 setBool 调用那个动画师。