我正在尝试制作一个脚本,当通电结束时,该脚本可以使玩家获得更强的攻击力。我可以通过增加健康来很好地工作,但是我似乎无法确定我在做错了什么。在过去的几天里,我一直在努力,但是我什么都没做。给出错误的行已注释,但可能很难看到。这是代码的第二行:
power.damagePerShot = power.damagePerShot + DamageBoost;
我认为我已经掌握了错误的性质,但是我不明白为什么会收到错误。如果power.damagePerShot
是从PlayerShooting
提取的,然后引用了正确的脚本,那么我将无法理解null引用的来源。
The conponent is referenced...
The script being referenced is attached to the object...
using UnityEngine;
public class ShootPowerUp : MonoBehaviour
{
public GameObject pickupEffect;
public PlayerShooting playerShooting;
public int DamageBoost = 100;
private void Update()
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
ShootPowerPickup(other);
}
}
void ShootPowerPickup(Collider player)
{
Instantiate(pickupEffect, transform.position, transform.rotation);
PlayerShooting power = player.GetComponent<PlayerShooting>();
power.damagePerShot = power.damagePerShot + DamageBoost; //This line is giving the error.
Destroy(gameObject);
}
}
答案 0 :(得分:2)
PlayerShooting
组件未附加到Player
GameObject,而是其子级之一
请像这样使用GetComponentInChildren
PlayerShooting power = player.GetComponentInChildren<PlayerShooting>();
你应该没事。