代码展示
玩家背包代码(挂载到玩家身上)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 玩家背包脚本,用来记录玩家道具
/// </summary>
public class MyBag : MonoBehaviour
{//public bool isHasKey=false;//是否有钥匙public List<string>keyList = new List<string>();//钥匙列表
}
钥匙代码(挂载到钥匙身上)
注意:钥匙身上必须要有触发器(挂载到钥匙身上即可)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Key : MonoBehaviour
{public string keyID;//钥匙编号private void OnTriggerEnter(Collider other){if(other.CompareTag("Player")){//修改玩家背包中的钥匙数据为真if(other.GetComponent<MyBag>()!=null){//other.GetComponent<MyBag>().isHasKey = true;other.GetComponent<MyBag>().keyList.Add(keyID);}Destroy(gameObject);}}
}
门的代码(挂载的门的触发器身上)
门的触发器可以单独拿出来,也可以就在门里面加组件
但是在门自身身上加组件时,触发器会随着门的移动而移动,所以用的时候要注意范围
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class _2_OpenDoor : MonoBehaviour
{[SerializeField] GameObject doorObj;//想要控制的门private bool isNear=false;//玩家是否到达门附近[SerializeField] private string doorID;//门编号// Start is called before the first frame updatevoid Start(){if (doorObj == null)Debug.LogError("请将门物体拽入参数栏!");}private void OnTriggerEnter(Collider other){if (other.CompareTag("Player")/*&&Input.GetKeyDown(KeyCode.E)*/){//doorObj.SetActive(false);//播放开门动画isNear=true;}}private void OnTriggerExit(Collider other){if (other.CompareTag("Player")){//播放关门动画doorObj.GetComponent<Animator>().SetBool("isOpen", false);isNear=false;}}// Update is called once per frameprivate void Update(){if (Input.GetKeyDown(KeyCode.L) && isNear){/* //检测玩家背包中是否存在钥匙if(GameObject.FindWithTag("Player").GetComponent<MyBag>().isHasKey){ //播放开门动画doorObj.GetComponent<Animator>().SetBool("isOpen", true); }*///播放开门动画if (GameObject.FindWithTag("Player").GetComponent<MyBag>() != null){var mybag = GameObject.FindWithTag("Player").GetComponent<MyBag>();foreach (var keyID in mybag.keyList){if (keyID.Equals(doorID)){doorObj.GetComponent<Animator>().SetBool("isOpen", true);}else{print("玩家没有这扇门的钥匙");}}}}else if(GameObject.FindWithTag("Player").GetComponent<MyBag>() != null){print("玩家没有任何钥匙钥匙");}if (Input.GetKeyUp(KeyCode.L) && isNear){//播放关门动画doorObj.GetComponent<Animator>().SetBool("isOpen", false);}}}