物體檢測(cè)和物體拾取與放置(代碼)

這里將視頻中的代碼放在這里:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
? ? float speed = 5;
? ? public Image background;
? ? public Text contetnTxt;
? ? GameObject obj = null;
? ? bool isPick = false;
? ? void Start()
? ? {
? ? ? ? background.gameObject.SetActive(false);
? ? }
? ? void Update()
? ? {
? ? ? ? if (Input.GetKey(KeyCode.W))
? ? ? ? {
? ? ? ? ? ? transform.Translate(Vector3.forward * speed * Time.deltaTime);
? ? ? ? }
? ? ? ? else if (Input.GetKey(KeyCode.S))
? ? ? ? {
? ? ? ? ? ? transform.Translate(Vector3.back * speed * Time.deltaTime);
? ? ? ? }
? ? ? ? if (Input.GetKey(KeyCode.A))
? ? ? ? {
? ? ? ? ? ? transform.Translate(Vector3.left * speed * Time.deltaTime);
? ? ? ? }
? ? ? ? else if (Input.GetKey(KeyCode.D))
? ? ? ? {
? ? ? ? ? ? transform.Translate(Vector3.right * speed * Time.deltaTime);
? ? ? ? }
? ? ? ? if (Input.GetKeyDown(KeyCode.F) && obj)
? ? ? ? {
? ? ? ? ? ? isPick = !isPick;
? ? ? ? ? ? if (isPick)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? contetnTxt.text = "F 放置";
? ? ? ? ? ? ? ? obj.transform.parent = transform;
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? contetnTxt.text = "F 拾取";
? ? ? ? ? ? ? ? obj.transform.parent = null;
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? private void OnTriggerEnter(Collider other)
? ? {
? ? ? ? if (other.gameObject)
? ? ? ? {
? ? ? ? ? ? obj = other.gameObject;
? ? ? ? ? ? background.gameObject.SetActive(true);
? ? ? ? }
? ? }
? ? private void OnTriggerExit(Collider other)
? ? {
? ? ? ? obj = null;
? ? ? ? background.gameObject.SetActive(false);
? ? }
}
