编辑-经过测试,我发现只有一部电梯可以动画。因此,如果我走进电梯,动画可能不会在其上播放,但会在另一个电梯上播放。我偶然发现了这一点。我以为动画师可以根据我接近的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);
}
}
}
我将其设置为参数为bool值的位置。当doorOpen为true且doorClose为false时,门将打开。当doorOpen为false且doorClose为true时,它将关闭。但是,如果两个值都为false,它将不会执行任何操作。
注意-我正在使用Unity 2019.1 Beta
答案 0 :(得分:0)
首先,问题是door = GameObject.FindWithTag("Elevator");
,这将返回它找到的带有该标签的第一个GameObject,这就是为什么当您敲击2个不同的触发器时,同一扇门会同时为两个动画设置动画。
在发现此脚本已经在您的电梯上之后,就不需要GameObject的门了,因为每个MonoBehavior都有对其自己的GameObject的引用,因此您只需创建一个Animator变量,然后像这样调用GetComponent():
public class Elevator : MonoBehavior
{
Animator myAnim;
void Start()
{
myAnim = GetComponent<Animator>();
myAnim.SetBool("doorOpen", true);
myAnim.SetBool("doorClose", false);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
myAnim.SetBool("doorOpen", true);
myAnim.SetBool("doorClose", false);
uiBg.enabled = true;
uiFg.enabled = true;
uiTxt.enabled = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
myAnim.SetBool("doorOpen", false);
myAnim.SetBool("doorClose", true);
uiBg.enabled = false;
uiFg.enabled = false;
uiTxt.enabled = false;
}
else
{
myAnim.SetBool("doorOpen", false);
myAnim.SetBool("doorClose", false);
}
}
}