我有一个运动学刚体和一个附加到该对象的 2d 碰撞器。我想做的是让我的角色发射照明弹来分散导弹对玩家的注意力。这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class flareShoot : MonoBehaviour
{
public GameObject flarePrefab; // Prefab for the flare
public Transform flareSpawnPoint; // Spawn point for the flare on the player
private GameObject currentFlare; // Current flare instance
public float fireForce = 10f; // Force to apply when firing the flare
void Start()
{
SpawnFlare();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && currentFlare != null)
{
FireFlare();
}
}
void SpawnFlare()
{
currentFlare = Instantiate(flarePrefab, flareSpawnPoint.position, flareSpawnPoint.rotation, flareSpawnPoint);
currentFlare.GetComponent<Rigidbody2D>().isKinematic = true; // Disable physics while attached
}
void FireFlare()
{
currentFlare.transform.SetParent(null); // Detach from player
Rigidbody2D rb = currentFlare.GetComponent<Rigidbody2D>();
rb.isKinematic = false; // Enable physics
rb.gravityScale = 1; // Enable gravity if needed
rb.AddForce(flareSpawnPoint.up * fireForce, ForceMode2D.Impulse); // Apply force to fire
currentFlare = null; // Reset the reference to the flare
}
}
虽然你的问题不太清楚,但你的问题已经很清楚了。发射第一个照明弹后,您的
currentFlare
为 null
。因此,如果您再次尝试 FireFlare,您将尝试设置 null
的变换,并尝试获取 null 的 Rigidbody2D。
这可以通过
FireFlare
中添加一行来解决:调用 SpawnFlare()
void FireFlare()
{
currentFlare.transform.SetParent(null); // Detach from player
Rigidbody2D rb = currentFlare.GetComponent<Rigidbody2D>();
rb.isKinematic = false; // Enable physics
rb.gravityScale = 1; // Enable gravity if needed
rb.AddForce(flareSpawnPoint.up * fireForce, ForceMode2D.Impulse); // Apply force to fire
currentFlare = null; // Reset the reference to the flare
SpawnFlare(); // Create a new flare after setting the previous one to null, so next time you can fire a new one.
}
}
如果您不想将发射照明弹与获取新照明弹联系起来,也可以将其放在更新中(以防您想在几秒钟后生成新的照明弹)。
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && currentFlare != null)
{
FireFlare();
SpawnFlare();
}
}