【问题标题】:how to move and recreate sprite in unity2D?如何在统一 2D 中移动和创建精灵?
【发布时间】:2019-04-10 21:00:09
【问题描述】:

大家好,我正在尝试用简单的代码进行拍摄 我有 2 个 C# 类,一个用于播放器动作,一个用于子弹

这是子弹碰撞类

void Start () {
    source.clip = clip;
    bullet = GetComponent<GameObject>();
    rb = GetComponent<Rigidbody2D>();
    bulletPos = player.position;
}

// Update is called once per frame
private void OnTriggerEnter2D(Collider2D wallCol)
{
    if (wallCol.gameObject.tag == "Wall")
    {
        Debug.Log("Wall Hited!");
        source.Play();
        Destroy(bulletPrefab,clip.length);
        if (bullet == null)
            Instantiate(bulletPrefab, bulletPos, Quaternion.identity);
    }
}
public void shoot()
{
    rb.velocity = rb.transform.right * bulletSpeed;
}

这是玩家运动类:

void Update()
{

    if (Input.GetKeyDown(KeyCode.Mouse0) && haveGlock == true)
    {
        bc.shoot();
        AudioSource.PlayOneShot(GlockClip);
    }

}

我确实在另一个类上使用了 shoot 方法,当该方法调用它时,向我显示对象引用未设置为对象的实例。 我也将对象拖放到所需的公共变量中 团结一致,但为什么它不起作用?

对不起,我的英语不好。

【问题讨论】:

  • 你的子弹有 Rigidbody2D 组件吗?好像是这个问题
  • 是的@Jichael
  • 为什么“如果 (bullet == null) 实例化(bulletPrefab, bulletPos, Quaternion.identity);” ??您创建了一个空的游戏对象,它甚至没有放入子弹中,子弹永远不会为空..
  • 销毁(bulletPrefab,clip.length); - 你试图摧毁一个预制件而不是它的一个实例,这也行不通
  • 谢谢..你有什么灵魂吗? @BugFinder

标签: c# windows unity3d


【解决方案1】:

确保在 Player Movement Class 中分配了“bc”。

我会在玩家运动课上做类似的事情。

void Update()
   {
    if (Input.GetKeyDown(KeyCode.Mouse0) && haveGlock == true)
    {
        BulletCollision bc = Instantiate(bulletPrefab, bulletPos, Quaternion.identity);
        bc.shoot();
        AudioSource.PlayOneShot(GlockClip);
    }

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多