Unity使用Instantiate实例化预制体的问题记录
不断创建的子弹实体能够按照辅助位置生成
using UnityEngine;
public class BulletFly : MonoBehaviour
{
public GameObject bulletPrefab;
public float bulletSpeed = 4f;
private FireOriginPosition fireOriginPosition;
private FireOriginDirection fireOriginDirection;
private Camera cam;
private void Start()
{
fireOriginPosition = GetComponentInChildren<FireOriginPosition>();
fireOriginDirection = GetComponentInChildren<FireOriginDirection>();
cam = GetComponentInChildren<Camera>();
}
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
LaunchBullet();
}
}
void LaunchBullet()
{
GameObject bullet = Instantiate(bulletPrefab, fireOriginPosition.transform.position, fireOriginPosition.transform.rotation);
Rigidbody bulletRigidbody = bullet.GetComponent<Rigidbody>();
if (bulletRigidbody != null)
{
bulletRigidbody.velocity = fireOriginDirection.transform.up * bulletSpeed;
}
Destroy(bullet, 5f);
}
}