gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:39:54 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com