unity3d c#调用脚本报错

using UnityEngine;
using System.Collections;

public class Destorybycontact : MonoBehaviour {
public GameObject explosion;
public GameObject playerexplosion;
public int score1;
private Gamecontrol game;

void start()
{
    GameObject gamecontrolobject = GameObject.FindWithTag("GameController");
    if (gamecontrolobject != null)
    {
        game = gamecontrolobject.GetComponent<Gamecontrol>();
    }
    if(gamecontrolobject == null)
    {
        Debug.Log("can't find 'Gamecontrol' scipt");
    }
}

void OnTriggerEnter(Collider other)
{
    if (other.tag == "boundary")
    { return; }
    Instantiate(explosion, transform.position, transform.rotation);
    if (other.tag == "Player")
    {
        Instantiate(playerexplosion, other.transform.position, other.transform.rotation);
    }
    game.addScore(score1);
    Destroy(other.gameObject);
    Destroy(gameObject);
}

}

报错NullReferenceException: Object reference not set to an instance of an object。显示这个是空值game.addScore(score1);。也不知道为什恶魔,求解

3个回答

你应该这么写吧

     GameObject gamecontrolobject = GameObject.FindWithTag("GameController");
    if (gamecontrolobject != null)
    {
        game = gamecontrolobject.GetComponent<Gamecontrol>();
        game.addScore(score1);          
    }
    else
        Debug.Log("can't find 'Gamecontrol' scipt");



你都不能确定game得到有效赋值,你就给加力明显不对的

qq_35219692
qq_35219692 我为了简略删掉了一些,现在更新了,求大神帮我看看
接近 4 年之前 回复

我是渣渣你试试下面这个

     void start()
    {

    }

    void OnTriggerEnter(Collider other)
    {
    if (other.tag == "boundary")
    { return; }
    Instantiate(explosion, transform.position, transform.rotation);
    if (other.tag == "Player")
    {
        Instantiate(playerexplosion, other.transform.position, other.transform.rotation);
    }
     GameObject gamecontrolobject = GameObject.FindWithTag("GameController");
    if (gamecontrolobject != null)
    {
        game = gamecontrolobject.GetComponent<Gamecontrol>();
        game.addScore(score1);          
    }
    else
        Debug.Log("can't find 'Gamecontrol' scipt");
    Destroy(other.gameObject);
    Destroy(gameObject);
}

空指针,找一下报错的地方的代码,看一下什么东西没找到,这种小问题,好解决

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐