0

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?

6
  • 1
    possible duplicate of What is a NullReferenceException and how do I fix it? Commented Mar 2, 2014 at 18:48
  • What line is the exception occurring on? Commented Mar 2, 2014 at 18:48
  • at ` Monster1 monster1 = new Monster1();` Commented Mar 2, 2014 at 18:50
  • Where is the camera object being instantiated? Commented Mar 2, 2014 at 18:51
  • @Daniel that was the error, I changed it to Camera.main. Thank you. Commented Mar 2, 2014 at 18:58

1 Answer 1

3

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>();
Sign up to request clarification or add additional context in comments.

2 Comments

thanx for the tips. I tried to do that and I am getting `Cannot implicity convert..."
Could you print the line that contains the error you are getting? I have a feeling you are instantiating a GameObject where you want to instantiate a Monster1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.