实例化

时间:2016-01-24 07:57:08

标签: c# unity3d nullreferenceexception

“对象引用未设置为对象的实例”错误仍在显示。

我在每个变量上都尝试过Debug.Log,没有错误。

这是我的代码:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlatformSpawn : MonoBehaviour {

    public GameObject platform;
    public GameObject life;
    private Vector3 platformrotation;
    private Vector2 platformpoint, lifepoint;
    private float platformrange, liferange;

    public List<Vector2> SpawnList = new List<Vector2> ();

    void Update () {
        float randposition = Random.Range (-10f, 10f); //x-axis
        platformrange -= 5; //y-axis
        float randrotation = Random.Range(-20f, 20f); //z-axis rotation
        liferange = platformrange + 1.56f;

        platformpoint = new Vector2 (randposition, platformrange);
        platformrotation = new Vector3 (0f, 0f, randrotation);
        lifepoint = new Vector2 (randposition, liferange);
        SpawnList.Add (platformpoint);

        GameObject Tlife = (GameObject)Instantiate (life, life.transform.position, life.transform.rotation);
        GameObject Tplatform = (GameObject)Instantiate (platform, platform.transform.position, platform.transform.rotation);

        Tlife.transform.position = lifepoint;
        Tplatform.transform.position = platformpoint;

        if (SpawnList.Count >= 10) {
            Tplatform.transform.rotation = Quaternion.Euler (platformrotation);
        }
    }
}

错误在

  

GameObject Tlife =(GameObject)实例化(生活,   life.transform.position,life.transform.rotation);

感谢4帮助^ _ ^

P.S。 预制件仍在没有任何问题的情况下实例化......

3 个答案:

答案 0 :(得分:3)

life必须是您已在编辑器中创建的预制件,并将其拖放到此对象的“检查器”窗口中。

确保:

  1. 创建预制件
  2. 在编辑器中选择此对象,以便显示检查器
  3. 将预制件拖放到&#34; life&#34;检查员中的字段

答案 1 :(得分:0)

请勿使用Instantiate(Object original, Vector3 position, Quaternion rotation) - 使用Instantiate(Object original)

在这种情况下,您尝试访问尚不存在的对象的位置和旋转(因此为空引用)。你试图实例化life并且在实例化时你告诉它在它的位置“产生”它 - 这没有任何意义。

使用Instantiate(Object original)将使用预制件中指定的位置和旋转来实例化您的对象 - 这正是您尝试做的事情。

不幸的是,似乎Unity的文档并没有真正说明Instantiate的后者重载,主要解释前者是如何工作的:http://docs.unity3d.com/ScriptReference/Object.Instantiate.html

编辑:同时检查你是否在Inspector中明确分配了预制件,否则你仍然会遇到问题,因为life没有引用任何东西。

答案 2 :(得分:0)

我想你们有些人没见过最后一部分,

  

P.S。预制件仍在没有任何问题的情况下实例化......

这是一个问题......预制件仍在实例化,就像没有任何问题一样,但问题是错误仍在“显示”

我猜这是Unity3D的一个错误,所以我再次使用了Debug.Log(生命),它显示它真的是空的......

我在生活变量中附加了一个预制件,并且仍在使用OnCollisionEnter2D ......

我还发现 - 是一种删除错误并仍然实例化的方法;

Private GameObject life;

void Start(){
life = new GameObject("name of the object");
//then attach some components for the new game object...
}

我用Collider2D尝试了它并且它有效,我仍然找到一种方法来附加一个带Sprite的SpriteRenderer ......

但是,谢谢你帮助的人^ _ ^