我有一个脚本来控制武器的拾取和放下,但是需要分配一些游戏对象才能起作用,但是由于我使用的是程序生成的地图(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>();
}
应该为您工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句