[英]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.