c# - 了解Unity的GameObject.Find()、GetComponent()和对象回收

标签 c# unity3d pool particle-system

Unity 新手。

所以我创建了一个简单的 Guzzle 闪光粒子动画,当玩家靠近他时应该在敌人的枪上显示它,模拟没有实际子弹的射击。但是,我在这部分 muzzleFlash.Play(); 中得到了一个空引用异常,我相信这是因为我实际上并没有使用我拥有的代码在启动函数中获取 Guzzle 闪光组件,实际上我知道是在进入 Debug模式后我发现的吗?我很难弄清楚如何访问该组件。下面是我的代码,我还张贴了我的层次结构的图片。提前致谢。

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

public class StaticShootingEnemy : MonoBehaviour
{

    [SerializeField] private float _range = 12f;
    private Transform _player;

    private bool _alive;
    private float _distance;
    private ParticleSystem muzzleFlash;

    // Use this for initialization
    void Start()
    {
        _player = GameObject.Find("Player").transform;
        _alive = true;
        muzzleFlash = (ParticleSystem)this.gameObject.GetComponent("muzzleFLash");

    }

    // Update is called once per frame
    void Update()
    {
        _distance = Vector3.Distance(this.transform.position, _player.transform.position);
        if (_alive && _distance < _range)
            AttackPlayer();
    }


    private void AttackPlayer()
    {
        //Turning enemy to look at player
        transform.LookAt(_player);
        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;
        if (Physics.SphereCast(ray, 0.75f, out hit))
        {
            //TODO: Fix enemy shooting fast when gettting close to him.
            GameObject hitObject = hit.transform.gameObject;
            if (hitObject.GetComponent<PlayerController>())
            {
                muzzleFlash.Play();
                Debug.Log("Player Hit!");
            }
            else
                muzzleFlash.Stop();
        }
    }

    public void SetAlive(bool alive)
    {
        _alive = alive;
    }

}

Hierarchy

最佳答案

您可能有一个对象“muzzleFlash”作为子对象来反对您的脚本。因此,在这种情况下,您最好引用名为 muzzleFlash 的 ParticleSystem 对象。

[SerializeField] private ParticleSystem muzzleFlash; // drag and drop your ParticleSystem muzzleFlash in inspector

或者至少你可以找到像这样的 muzzleFlash

GameObject muzzleFlashObj = GameObject.Find("muzzleFlash"); ParticleSystem muzzleFlash = muzzleFlashObj.GetComponent<ParticleSystem>();

在您的情况下,它为空,因为该对象上可能没有名为 MuzzleFlash 的组件。您要获取的组件是 ParticleSystem。

关于c# - 了解Unity的GameObject.Find()、GetComponent()和对象回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52824146/

相关文章:

c# - 如何在 C# 中找到给定开始、结束和 2 个交点的 BezierSegment 的控制点 - 又名三次贝塞尔曲线 4 点插值

c# - 在 Unity 中创建浮力船

c# - 统一获取触摸屏设备(如 androidPhone)的触摸输入?

java - javax.crypto.Cipher 的输出灵活性,re : fixed-size ByteBuffers

c# - 如何使用 keybd_event 模拟 Ctrl A + Ctrl C

javascript - 从js代码赋值给mvc razor的隐藏字段

c# - 如何为 Visual Studio 2015 社区版使用 Type.GetTypeFromProgID()

ios - Unity iOS 屏幕在启动时变黑几秒钟

python - Gevent 与 Stream Server 的数据库连接池

java - Java Web 服务器中的线程池