#object #user-interface
#объект #пользовательский интерфейс
Вопрос:
В настоящее время пытаюсь сделать игру «Стелс» сверху вниз. К сожалению, при переходе на следующий уровень пользовательский интерфейс не хочет всплывать, когда меня ловит враг. Обычно предполагается, что на моем экране появится текст с надписью «Вас поймали», но при переключении уровней с помощью триггера он, похоже, не позволяет всплывать пользовательскому интерфейсу.
Код пользовательского интерфейса
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameUI : MonoBehaviour
{
public GameObject gameLoseUI;
public GameObject gameWinUI;
bool gameIsOver;
void Start()
{
Guard.OnGuardHasSpottedPlayer = ShowGameLoseUI;
FindObjectOfType<Player>().OnReachedEndOfLevel = ShowGameWinUI;
}
void Update()
{
if (gameIsOver){
if (Input.GetKeyDown(KeyCode.Space)){
SceneManager.LoadScene(0);
}
}
}
void ShowGameWinUI(){
OnGameOver(gameWinUI);
}
void ShowGameLoseUI(){
OnGameOver(gameLoseUI);
}
public void OnGameOver (GameObject gameOverUI)
{
gameOverUI.SetActive(true);
gameIsOver = true;
Guard.OnGuardHasSpottedPlayer -= ShowGameLoseUI;
FindObjectOfType<Player>().OnReachedEndOfLevel -= ShowGameWinUI;
}
}
Защитный код
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Guard : MonoBehaviour
{
public static event System.Action OnGuardHasSpottedPlayer;
public float speed = 5;
public float waitTime = .3f;
public float turnSpeed = 90;
public float TimeToSpotPlayer = .5f;
public Light spotlight;
public float ViewDistance;
public LayerMask viewMask;
float ViewAngle;
float playerVisibleTimer;
public Transform PathHolder;
Transform player;
Color OriginalSpotlightColour;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
ViewAngle = spotlight.spotAngle;
OriginalSpotlightColour = spotlight.color;
Vector3[] waypoints = new Vector3[PathHolder.childCount];
for (int i = 0; i < waypoints.Length; i ) {
waypoints[i] = PathHolder.GetChild(i).position;
waypoints[i] = new Vector3(waypoints[i].x, transform.position.y, waypoints[i].z);
}
StartCoroutine(Followpath(waypoints));
}
void Update()
{
if (CanSeePlayer()){
playerVisibleTimer = Time.deltaTime;
}else{
playerVisibleTimer -= Time.deltaTime;
}
playerVisibleTimer = Mathf.Clamp(playerVisibleTimer, 0, TimeToSpotPlayer);
spotlight.color = Color.Lerp(OriginalSpotlightColour, Color.red, playerVisibleTimer / TimeToSpotPlayer);
if (playerVisibleTimer >= TimeToSpotPlayer)
{
if (OnGuardHasSpottedPlayer != null)
{
OnGuardHasSpottedPlayer();
}
}
}
bool CanSeePlayer()
{
if (Vector3.Distance(transform.position,player.position) < ViewDistance)
{
Vector3 dirToPlayer = (player.position - transform.position).normalized;
float angleBetweenGuardAndPlayer = Vector3.Angle(transform.forward, dirToPlayer);
if (angleBetweenGuardAndPlayer < ViewAngle / 2f)
{
if (!Physics.Linecast (transform.position, player.position, viewMask)) {
return true;
}
}
}
return false;
}
IEnumerator Followpath(Vector3[] waypoint) {
transform.position = waypoint[0];
int targetWaypointIndex = 1;
Vector3 targetWaypoint = waypoint [targetWaypointIndex];
transform.LookAt (targetWaypoint);
while (true)
{
transform.position = Vector3.MoveTowards (transform.position, targetWaypoint, speed * Time.deltaTime);
if (transform.position == targetWaypoint)
{
targetWaypointIndex = (targetWaypointIndex 1) % waypoint.Length;
targetWaypoint = waypoint [targetWaypointIndex];
yield return new WaitForSeconds (waitTime);
yield return StartCoroutine (TurnToFace (targetWaypoint));
}
yield return null;
}
}
IEnumerator TurnToFace(Vector3 lookTarget)
{
Vector3 dirToLookTarget = (lookTarget-transform.position).normalized;
float targetAngle = 90- Mathf.Atan2 (dirToLookTarget.z, dirToLookTarget.x) * Mathf.Rad2Deg;
while (Mathf.Abs(Mathf.DeltaAngle(transform.eulerAngles.y, targetAngle)) > 0.05f)
{
float angle = Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetAngle, turnSpeed * Time.deltaTime);
transform.eulerAngles = Vector3.up * angle;
yield return null;
}
}
void OnDrawGizmos()
{
Vector3 startPosition = PathHolder.GetChild(0).position;
Vector3 previousPosition = startPosition;
foreach (Transform Waypoint in PathHolder)
{
Gizmos.DrawSphere(Waypoint.position, .3f);
Gizmos.DrawLine(previousPosition, Waypoint.position);
previousPosition = Waypoint.position;
}
Gizmos.DrawLine(previousPosition, startPosition);
Gizmos.color = Color.red;
Gizmos.DrawRay(transform.position, transform.forward * ViewDistance);
}
}
Перемещение сцены
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MoveScene : MonoBehaviour
{
[SerializeField] private string loadLevel;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
SceneManager.LoadScene(loadLevel);
}
}
}
Код игрока
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
public class Player : MonoBehaviour{
public event System.Action OnReachedEndOfLevel;
public float moveSpeed = 7;
public float SmoothMoveTime = .1f;
public float TurnSpeed = 8;
float angle;
float SmoothInputMagnitude;
float SmoothMoveVelocity;
Vector3 velocity;
new Rigidbody rigidbody;
bool disabled;
void Start()
{
rigidbody = GetComponent<Rigidbody>();
Guard.OnGuardHasSpottedPlayer = Disable;
}
void Update()
{
Vector3 inputDirection = Vector3.zero;
if (!disabled)
{
inputDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0,
Input.GetAxisRaw("Vertical")).normalized;
}
float inputMagnitude = inputDirection.magnitude;
SmoothInputMagnitude = Mathf.SmoothDamp(SmoothInputMagnitude,
inputMagnitude, ref SmoothMoveVelocity, SmoothMoveTime);
float targetAngle = Mathf.Atan2 (inputDirection.x, inputDirection.z) * Mathf.Rad2Deg;
angle = Mathf.LerpAngle(angle, targetAngle, Time.deltaTime * TurnSpeed * inputMagnitude);
velocity = transform.forward * moveSpeed * SmoothInputMagnitude;
}
void OnTriggerEnter(Collider hitcollider){
if (hitcollider.tag =="Finish")
{
Disable();
if (OnReachedEndOfLevel != null)
{
OnReachedEndOfLevel();
}
}
}
void Disable()
{
disabled = true;
}
void FixedUpdate()
{
rigidbody.MoveRotation(Quaternion.Euler(Vector3.up * angle));
rigidbody.MovePosition(rigidbody.position velocity * Time.deltaTime);
}
private void OnDestroy()
{
Guard.OnGuardHasSpottedPlayer -= Disable;
}
}
Комментарии:
1. Привет, добро пожаловать в SO. Я предлагаю добавить больше деталей и, возможно, больше примеров кода к вашему вопросу, чтобы получить больше информации. Это не то, на что кто-то мог бы ответить, не зная больше о вашей кодовой базе.
2. @JohannBurgess Вот и весь код, оцените это.