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?

Avraam Mavridis
  • 7,742
  • 14
  • 68
  • 117

1 Answers1

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>();
pek
  • 16,939
  • 27
  • 83
  • 98
  • thanx for the tips. I tried to do that and I am getting `Cannot implicity convert..." – Avraam Mavridis Mar 03 '14 at 07:02
  • 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 – pek Mar 03 '14 at 19:57