c# - 由于某种原因我的手榴弹没有初始化

标签 c# unity-game-engine

我有 2 个问题。 (1) 由于某种原因,我的手榴弹没有初始化。 (2) Transform.LookAt(Player) 不起作用。我正在尝试制作一个会 throw 手榴弹的漂浮怪物。我知道 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);
    }
}

最佳答案

我发现它没有初始化的原因是因为行 bulletObject.transform.forward = FloatingMonster.transform.forward; 。我认为这在某种程度上阻碍了它。

关于c# - 由于某种原因我的手榴弹没有初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67928686/

相关文章:

c# - 为什么 RowVersion 属性在发生两个并发更改时不引发乐观并发异常?

C# 帮助将此代码从 VB.NET 转换为 C#

c# - Unity2D 拍摄对象随角色转动但不应该转动

c# - 字符串长度不等于字符串数据 Unity C#

c# - 在 C 和 C# 中处理数组

c# - WPF 可能与 where 子句绑定(bind)?

c# - MVC中如何让访问者等待一个方法完成?

android - facebook unity sdk获取用户的名字和姓氏:

ios - 未找到架构 ARM64 clang 的符号 - 错误 : linker command failed with exit code 1 (use -v to see invocation)

c# - 保存和加载音频