首页 > 解决方案 > 出于某种原因,我的手榴弹没有初始化

问题描述

我有2个问题。(1) 出于某种原因,我的手榴弹没有初始化。(2) Transform.LookAt(Player) 不起作用。我正在尝试制作一个会投掷手榴弹的漂浮怪物。我知道 IEnumerator 运行(我放了一个 debug.Log),所以我知道手榴弹问题不是因为它没有运行。我不确定为什么 transform.Lookat 不起作用。谢谢您的帮助!

脚本:(对不起,如果代码不好,我是编程菜鸟)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ZKAttack_lvl3 : MonoBehaviour
{
    public Transform Player;
    public float MoveSpeed = 3.5f;
    public float InRadius = 4.0f;
    public float AttackRange = 1.0f;

    private Coroutine hasCourutineRunYet;

    public GameObject grenade;
    public GameObject FloatingMonster;

    private Animator anim;
    private Rigidbody rigid;

    private void Start()
    {
        anim = GetComponent<Animator>();
        Player = GameObject.FindGameObjectsWithTag("Player")[0].transform;

        rigid = GetComponent<Rigidbody>();
        
    }

    void Update()
    {
        transform.LookAt(Player);

        float dstSqr = (Player.position - transform.position).sqrMagnitude;
        bool inRadius = (dstSqr <= InRadius * InRadius);
        bool inAttackRange = (dstSqr <= AttackRange * AttackRange);
        anim.SetBool("inRadius", inRadius);
        anim.SetBool("AttackingPlayer", inAttackRange);
        if (inRadius)
        {
            transform.position += transform.forward * MoveSpeed * Time.deltaTime;
        }

        rigid.AddForce(1, 10, 1);

        if (inAttackRange)
        {
            if (hasCourutineRunYet == null)
            {
                hasCourutineRunYet = StartCoroutine(GrenadeAttack());
            }
        }
    }

    IEnumerator GrenadeAttack()
    {
        GameObject bulletObject = Instantiate(grenade);
        bulletObject.transform.position = FloatingMonster.transform.position + FloatingMonster.transform.forward;
        bulletObject.transform.forward = FloatingMonster.transform.forward;

        yield return new WaitForSeconds(2.0f);
    }
}

标签: c#unity3d

解决方案


我发现它没有初始化的原因是因为线bulletObject.transform.forward = FloatingMonster.transform.forward; 。我认为这以某种方式阻碍了它。


推荐阅读