为什么我的输入在敌人游戏对象被摧毁后没有生成对象



[在此处输入图像描述][1]最初,这是一个空引用异常,这是使用/引用变量但尚未初始化时出现的问题。我使用了一个 if 语句来检查实例是否不为 null,它会实例化。Null 引用异常问题已消失,但仍然无法实例化。

废稿.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScrapScript : MonoBehaviour 
{
public GameObject[] ScrapSprite;
EnemyScript Es;

void Start () 
{
    Es = GameObject.FindObjectOfType<EnemyScript> ();
    foreach(GameObject SSprite in ScrapSprite)
    {
        print (SSprite);
    }

}

void Update () 
{
}
public void SpawnScraps()
{
    if(Es != null   )
    {
        Instantiate (ScrapSprite[0], Es.transform.position, Es.transform.rotation);
    }
}

}

敌人被摧毁.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyDestroyed : MonoBehaviour {
BulletScript.BulletType theBulletType = 0;

ScrapScript SS;
void Start () 
{
    SS = GameObject.FindObjectOfType<ScrapScript> ();
}
void Update () 
{
}

void OnTriggerEnter(Collider collider)
{
    if(collider.tag == "PlayerBullet" && theBulletType == BulletScript.BulletType.PlayerBullet)
    {
        print ("ship destroyed");
        Destroy(collider.gameObject);
        Destroy(gameObject);
        SS.SpawnScraps ();  
    }
    if(collider.tag == "L.Collider Det")
    {
        Destroy(gameObject);
    }
}

}

敌人脚本.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour {
public int enemyHP;
public float enemySpeed;
public GameObject enemyBullet;
internal int enemyBulletCount = 0;
public int maxAllowableBulletCount;
public Transform enemyBulletSpawn;
public EnemyType ET;
public enum EnemyType
{
    Grunt,
    Boss,
}
void Awake()
{
    StartCoroutine (MyShootCoroutine ());
}
void Start () 
{
}

void Update () 
{
    if (ET == EnemyType.Grunt) 
    {
        transform.Translate (-enemySpeed * Time.deltaTime, 0f, 0f);
    }
}
IEnumerator MyShootCoroutine()
{

    for(enemyBulletCount = 0; enemyBulletCount <= maxAllowableBulletCount; enemyBulletCount++)
    {
        yield return new WaitForSeconds (1.5f);
        Instantiate (enemyBullet, enemyBulletSpawn.position, enemyBulletSpawn.rotation);
    }   
}   

}

期望:我对我的代码的期望是生成一种名为"废料"的拾取货币,当敌人被摧毁时,玩家将在接触时获得这种货币。它准确地在敌人被玩家的子弹摧毁的地方生成。

截图链接[在此输入图像描述][1][1]: https://i.stack.imgur.com/6iq11.png

鉴于您在 Es 对象的 SpawnScraps 方法中存在空引用异常,唯一的问题是当您的方法被称为 Es 对象时,该对象已被销毁。

假设您在尝试对他调用方法之前杀死了您的 ennemy 实例,您会得到一个空引用异常:

Destroy(collider.gameObject);
Destroy(gameObject);
SS.SpawnScraps ();

只需在销毁 ennemy 游戏对象之前调用 SpawnScraps 方法:

SS.SpawnScraps ();
Destroy(collider.gameObject);
Destroy(gameObject);

在你的废品脚本中,你的 Es 可能仍然是空的。这可能是因为您的脚本仅在 Start(( 期间找到 Enemyscript。您可以删除此检查并通过将敌人的转换传递到您的 SpawnScraps 函数中来简化事情。

在敌人被摧毁中,将您的行更改为:

SS.SpawnScraps (transform);  

在 Scraptscript 中将现有函数更改为:

public void SpawnScraps(Transform enemy)
{
    Instantiate (ScrapSprite[0], enemy.position, enemy.rotation);
}

最新更新