简体   繁体   中英

C# NullReferenceException in unity3d

I have this class:

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 () {

    }

When I am trying to instantiate an object of that class there is a NullReferenceException .

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

    }

Any idea why this is happening and how can I fix it?

2 things: You should never use constructors in your MonoBehaviours. Use Awake instead. So replace

public Monster1(){

with

public void Awake(){

Second, you never instantiate a MonoBehaviour with "new". You need to add it to a game object:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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