现在我想让我的实例化子弹在与墙碰撞时销毁,但是Visual Studio说'bullet'在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);
}
}
}
你不能这样做,你不能改变方法签名并将变量作为方法参数传递,因为它是一个统一事件函数,所以它必须保持原样。相反,把它变成一个字段。
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;
private GameObject bullet;
// Update is called once per frame
void Update()
{
if (firing == false)
{
if (Movement.ismoving == false)
{
firing = true;
StartCoroutine(Shoot());
}
}
}
IEnumerator Shoot()
{
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);
}
}
}