[英]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
. 当我尝试实例化该类的对象时,存在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. 2件事情:绝对不要在MonoBehaviours中使用构造函数。 Use Awake instead. 请改用“唤醒”。 So replace 所以更换
public Monster1(){
with 与
public void Awake(){
Second, you never instantiate a MonoBehaviour with "new". 其次,您永远不要使用“新”实例化MonoBehaviour。 You need to add it to a game object: 您需要将其添加到游戏对象中:
GameObject myGameObject = ...
myGameObject.AddComponemt<Momster1>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.