我正在尝试制作一个动画,在输入触发器后单击按钮时总是会发生



我正在用unity 2022制作一款游戏,并且正在努力制作这个动画[bool turn true]在输入触发器并按下&;e &;键后。然后走假之后还抱着&;不按还是不按。我也在努力获取关键的东西。这不是工作伙伴,我已经尝试了几个小时的斗争,所以是的。这是我的代码。它基本上是有人按下一个按钮(我在unity中使用的对象),使它点击,直到你再次点击它,请帮助这是一个学校的暑期项目!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
class Fixedpress : MonoBehaviour
{
public Animator Tributton;
bool YUIp = false;
// Start is called before the first frame update
void OnTriggerEnter(Collider other)
{
if(other.tag == "player")
{
YUIp = true;
}
}
void OnTriggerStay(Collider other)
{

if (other.tag == "Player" && YUIp == true)
{
if (Input.GetKeyDown(KeyCode.E))
{
Tributton.SetBool("Fiveyon", true);
Debug.Log("THY");
}
else if (Input.GetKey(KeyCode.E))
{
Tributton.SetBool("Fiveyon", false);
Debug.Log("THe");
}
else if (Input.GetKeyUp(KeyCode.Return))
{
Tributton.SetBool("Fiveyon", false);
Debug.Log("THane");
}
}

}
void OnTriggerExit(Collider other)
{
if(other.tag == "Player")
{
YUIp = false;
}
}
}

我最需要帮助的是按e代码的东西,使工作,所以是的:D

谢谢

对不起,语法不好,它是3 am rn

我想我现在明白了。

你想要的

  • Player必须在触发器中才能启动动画
  • 按E应该只触发动画一次

在这种情况下,我不会使用Bool参数,而是使用Trigger,然后是Animator.SetTrigger

你的过渡应该有点像,例如

Idle State --condition-Fiveyon--> Your Animation
Your Animation --exit-time-no-further-condition--> Idle State

那么你可以这样做,例如:

public class Fixedpress : MonoBehaviour
{
public Animator Tributton;
private Coroutine routine;
private void OnTriggerEnter(Collider other)
{
// not sure if needed right now, some of the events are triggered even on disabled components
if(!enabled) return;
// in general rather use CompareTag instead of ==
// it is slightly faster and also shows an error if the tag doesn't exist instead of failing silent
if(!other.CompareTag("player")) return;

// just in case to prevent concurrent routines
if(routine != null) StopCoroutine(routine);
// start a new Coroutine
routine = StartCoroutine(WaitForKeyPress());
}
private IEnumerator WaitForKeyPress()
{
// check each FRAME if the key goes down
// This is way more reliable as OnTriggerStay which is called
// in the physics loop and might skip some frames
// This also prevents from holding E while entering the trigger, it needs to go newly down 
yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.E));

// set the trigger once and finish the routine
// There is no way to trigger twice except exit the trigger and enter again now
Tributton.SetTrigger("Fiveyon");
Debug.Log("Fiveyon!");
// If you even want to prevent this from getting triggered ever again simply add
enabled = false;
// Now this can only be triggered ONCE for the entire lifecycle of this component 
// (except you enable it from the outside again of course)
}
void OnTriggerExit(Collider other)
{
if(!other.CompareTag("player")) return;
// when exiting the trigger stop the routine so later button press is not handled
if(routine != null) StopCoroutine(routine);
}
}