c# - 通过使用脚本名称的字符串(或不使用)使用 GetComponent 获取游戏对象的脚本
问题描述
我正在尝试制作一个枪支/武器系统,通过使用一个包含“该特定武器的射击机制”的脚本而不是所有枪的一个脚本(因为我正在制作的武器有自己的特点)。
我所做的是:
基本上我有3个主要脚本,
- 来自玩家的作为输入的脚本(在玩家的游戏对象上)
- 保存鼠标左右键射击机制脚本的脚本(在武器游戏对象上)
- 执行射击机制的脚本(在武器上)
我有一个玩家本身的脚本(用于武器控制),所以当玩家点击 LMB 时,它将获得它持有的当前武器,然后获得第一个武器脚本(第一个),它持有其他射击技工脚本(第二个)然后运行一个名为“LMB()”的函数,该函数在第三个脚本中运行一个函数,该函数将用于拍摄 ( 3rd )。
第一个脚本
public class PlayerShooting : MonoBehaviour
{
public GameObject[] WeaponList;
public int ListLength;
public int currentWeapon;
// Start is called before the first frame update
void Start()
{
ListLength = WeaponList.Length;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
// get the 2nd script for the current weapon and runs "LMB()"
}
}
}
第二个脚本
public class WeaponScript : MonoBehaviour
{
public GameObject selfRef;
public int WeaponId;
public void LMB()
{
//I don't understand this one
//var type = Type.GetType(WeaponId + "LMB");
//selfRef.GetComponent(type);
// or maybe?
//selfRef.GetComponent<WeaponId + "LMB">().shoot();
}
}
第三个脚本
public void shoot()
{
//the shooting happens
}
如果让您感到困惑,我很抱歉,请随时提出问题。
解决方案
有一个射击行为的中级课程怎么样?
public abstract class WeaponScript : MonoBehaviour
{
public virtual void PrimaryFire(){}
public virtual void SecondaryFire(){}
}
然后导出例如
public class LaserScript: WeaponScript {
public override void PrimaryFire() { /* pew pew! */ }
}
并将其连接到您的激光枪上。
然后你应该能够
if (Input.GetKeyDown(KeyCode.Mouse0)) {
// Get the first weapon script attached to the weapon
var weaponScript = WeaponList[currentWeapon].GetComponent<WeaponScript>();
weaponScript.PrimaryFire();
}
推荐阅读
- oracle - 函数在 PL/SQL 中有效,但在 PowerBi 中无效
- android - 在 avd 上运行 ar 核心示例
- python - 修改大量 DICOM (.dcm) 文件。
- php - 为什么页面加载这么久?
- node.js - 使用firebase云功能将数据从一个node1子节点复制到另一个node2子节点
- react-native - 带有变量占位符的文本输入并在按钮单击时清除
- ios - 无法完全安装 pod 'FBSDKLoginKit' 它就停在那里
- python-3.x - 熊猫如何将二维数据帧转换为一维数据帧
- c# - 隐藏或保护 .txt 保存数据 c#
- python - Python 多处理,TypeError