OnMouseDown()null引用异常

时间:2018-01-03 16:07:36

标签: c# unity3d onmousedown

public class TowerNode : MonoBehaviour {

public bool IsShopOpen=false;

//Z position
public Vector3 positionOffSet;

//colors
public Color hoverColor;
private Color startColor;

//GameObjects
public GameObject turret;

//shop
public Shop shop;

//Build Manager
BuildManager buildManager;

void Start()
{
    rend=GetComponent<Renderer>();
    startColor = rend.material.color;
    buildManager = BuildManager.instance;
    shop = GetComponent<Shop>();
}


//When mouse is on the turret node
public void OnMouseDown()
{    
    Debug.Log("Mouse is Down");
    bool IsShopOpen  = true;
    if (IsShopOpen == true)
    {
        Debug.Log("shop is open");
        shop.onEnable();
    }

    if (EventSystem.current.IsPointerOverGameObject())
    {          
        return;
    }
    if (!buildManager.CanBuild)
    {
        return;
    }
    if (turret != null)
    {
        Debug.Log("Cant Build Here!!!");
        return;
    }       

    buildManager.BuildTurretOn(this);

}

商店的另一个剧本是:

public class Shop : MonoBehaviour
{
public TurretBlueprint Archery;
public TurretBlueprint Treb;
public TurretBlueprint Workamp;
public TurretBlueprint Barracks;

public Button Archeryy;
public Button Trebb;
public Button WorkCampp;
public Button Barrackss;

BuildManager buildManager;


void Start()
{
    buildManager = BuildManager.instance;
    disableAllButtons();
    //OnEnable();
}

public void SelectArchery()
{
    buildManager.SelectTurretToBuild(Archery);
    Debug.Log("archery!!!!");

}
public void SelectTreb()
{
    buildManager.SelectTurretToBuild(Treb);
    Debug.Log("Treb!!!!");
}
public void SelectWorkamp()
{
    buildManager.SelectTurretToBuild(Workamp);
    Debug.Log("Work Camp!!!!");
}
public void SelectBarracks()
{
    buildManager.SelectTurretToBuild(Barracks);
    Debug.Log("Barracks!!!!");
}


public void onEnable()
{
    Archeryy.gameObject.SetActive(true);
    Trebb.gameObject.SetActive(true);
    WorkCampp.gameObject.SetActive(true);
    Barrackss.gameObject.SetActive(true);

}

public void disableAllButtons()
{
    Archeryy.gameObject.SetActive(false);
    Trebb.gameObject.SetActive(false);
    WorkCampp.gameObject.SetActive(false);
    Barrackss.gameObject.SetActive(false);
}

}

我需要当我点击游戏对象时,商店会打开它下面有几个按钮,但它给了我:

  

“NullReferenceException:对象引用未设置为对象的实例   TowerNode.OnMouseDown()(在Assets / Scripts / TowerNode.cs:51)   UnityEngine.SendMouseEvents:DoSendMouseEvents(的Int32)“

我不明白为什么。

1 个答案:

答案 0 :(得分:2)

您获得的错误意味着OnMouseDown函数中的对象在执行时为空:

  

NullReferenceException:对象引用未设置为对象的实例TowerNode.OnMouseDown()(在Assets / Scripts / TowerNode.cs:51)

您应该查看TowerNode.cs的ine 51并确定该行上的null。 shopbuildManager可以为空吗?在您初始化TowerNode对象之前,可能会触发此事件。

您似乎正在尝试从完全不相关的GameObject访问组件(Shop)。如果您希望所有TowerNode个对象都引用Shop,那么您可以使用GameObject.Find。但这并不是真的值得推荐的;似乎有更好的方法来链接这两个对象,但我不确定你的用例。