c# - 如何在游戏开始时启动的预制件上的检查器中分配游戏对象变量?
问题描述
我有一个控制武器拾取和放下的脚本,但它需要分配一些游戏对象才能工作,但我所有的武器都是在游戏开始时生成的,因为我使用的是程序生成的地图(DunGen 资产)。我该如何分配它们?
我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponsPickup : MonoBehaviour
{
public Rigidbody rb;
public BoxCollider coll;
public Transform player, gunContainer, fpsCam;
public float pickUpRange;
public float dropForwardForce, dropUpwardForce;
public bool equipped;
public static bool slotFull;
private void Start()
{
//Setup
if (!equipped)
{
rb.isKinematic = false;
coll.isTrigger = false;
}
if (equipped)
{
rb.isKinematic = true;
coll.isTrigger = true;
slotFull = true;
}
}
private void Update()
{
//Check if player is in range and "E" is pressed
Vector3 distanceToPlayer = player.position - transform.position;
if (!equipped && distanceToPlayer.magnitude <= pickUpRange && Input.GetKeyDown(KeyCode.E) && !slotFull) PickUp();
//Drop if equipped and "Q" is pressed
if (equipped && Input.GetKeyDown(KeyCode.Q)) Drop();
}
private void PickUp()
{
equipped = true;
slotFull = true;
//Make weapon a child of the camera and move it to default position
transform.SetParent(gunContainer);
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.Euler(Vector3.zero);
transform.localScale = Vector3.one;
//Make Rigidbody kinematic and BoxCollider a trigger
rb.isKinematic = true;
coll.isTrigger = true;
}
private void Drop()
{
equipped = false;
slotFull = false;
//Set parent to null
transform.SetParent(null);
//Make Rigidbody not kinematic and BoxCollider normal
rb.isKinematic = false;
coll.isTrigger = false;
//Gun carries momentum of player
rb.velocity = player.GetComponent<Rigidbody>().velocity;
//AddForce
rb.AddForce(fpsCam.forward * dropForwardForce, ForceMode.Impulse);
rb.AddForce(fpsCam.up * dropUpwardForce, ForceMode.Impulse);
//Add random rotation
float random = Random.Range(-1f, 1f);
rb.AddTorque(new Vector3(random, random, random) * 10);
}
}
解决方案
首先分配对象武器的标签(或您需要编写脚本的任何对象),然后是:
public Transform _weapon;
void Start() {
_weapon = GameObject.FindGameObjectWithTag("weapon").GetComponent<_weapon>();
}
应该为你工作。
推荐阅读
- python - 如何将变量值作为参数传递给格式化函数
- java - 为什么线程池中的线程无法执行?
- c# - 使用视图模型进行远程验证。列出视图模型中的属性
- r - 过滤 group_by + mutate 不像 group_by + summarise 在 dplyr R
- c - 理解指向整数类型指针数组的指针
- javafx - javafx中场景的主要作用是什么?
- haskell - State Monad 是如何获取初始状态的?
- python - 排序后如何从两个列表中获取最大元素的索引?
- javascript - 如何编码以提高 Tesseract.js 的准确性,并更多地支持正确的 OCR,其标签与 Google Cloud Vision 相同,并同时支持 2 种语言?
- swift - 我的 Userdefault 没有保存数据,也没有被 ObjectMapper 快速映射