繁体   English   中英

unity3d中的C#NullReferenceException

[英]C# NullReferenceException in unity3d

我有这个课:

using UnityEngine;
using System.Collections;

public class Monster1 : MonoBehaviour {

    private GameObject monster_;
    // Use this for initialization

    public Monster1(){
        monster_ = (GameObject)Instantiate(Resources.Load("Monster1"));
        float height = Random.Range(0, Screen.height);
        Vector2 monster1position = new Vector2(Screen.width, height);
        monster1position = camera.ScreenToWorldPoint(monster1position);
        monster_.transform.position = monster1position;
    }
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

当我尝试实例化该类的对象时,存在NullReferenceException

void Start () {
        Monster1 monster1 = new Monster1();

    }

知道为什么会发生这种情况,我该如何解决?

2件事情:绝对不要在MonoBehaviours中使用构造函数。 请改用“唤醒”。 所以更换

public Monster1(){

public void Awake(){

其次,您永远不要使用“新”实例化MonoBehaviour。 您需要将其添加到游戏对象中:

GameObject myGameObject = ...
myGameObject.AddComponemt<Momster1>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM