【发布时间】:2021-10-01 02:19:14
【问题描述】:
现在我希望实例化的子弹在与墙壁碰撞时销毁,但 Visual Studio 表示 OnTriggerEnter2D 函数的当前上下文中不存在“子弹”。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace work.working.worked
{
public class Shooting : MonoBehaviour
{
public static bool firing;
public Transform firepoint;
public GameObject bulletprefab;
public float bulletspeed;
// Update is called once per frame
void Update()
{
if (firing == false)
{
if (Movement.ismoving == false)
{
firing = true;
StartCoroutine(Shoot());
}
}
}
IEnumerator Shoot()
{
GameObject bullet = Instantiate(bulletprefab, firepoint.position, firepoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firepoint.up * bulletspeed, ForceMode2D.Impulse);
yield return new WaitForSeconds(0.5f);
firing = false;
}
private void OnTriggerEnter2D(Collider2D collision)
{
Destroy(bullet);
}
}
}
【问题讨论】:
-
如果你想在其他地方使用它,它不应该是局部变量。
-
它不会做你想做的事,因为你想在当子弹碰撞时摧毁子弹,而不是在这个对象产生子弹碰撞 ... => 在子弹预制件上放置一个专用组件来跟踪
OnTriggerEnter...