如何附加' TextMesh' Unity 3D上的克隆对象的属性

时间:2016-03-26 00:48:15

标签: c# unity3d

我在Unity 3D上生成类对象的动态实例并且运行良好,但是,当我尝试添加额外的组件TextMesh时,我无法访问他们分配文字。 代码是:

Bubble.cs

public class Bubble : MonoBehaviour {
    Vector3 offset = Vector3.zero;
    Vector3 oldpos = Vector3.zero;
    public Team team = Team.Green;
    public Color teamColor;
    float blastRange = 4.0f;
    float moved = 0;
    public TextMesh nText = new TextMesh();

    void Start () {
        score = (Score)FindObjectOfType(typeof(Score));
        Game.game.bubbles.Add(this);

        nText.text = "123";
    }

}

但是,当我尝试访问nText属性时,始终是null。 此外,我无法将此TextMesh链接到场景中定义的组件,因为所有气泡应具有不同的值。

如何解决?

错误是:UnassignedReferenceException: The variable nText of Bubble has not been assigned. You probably need to assign the nText variable of the Bubble script in the inspector.

2 个答案:

答案 0 :(得分:0)

尝试

nText = gameObject.AddComponent<TextMesh>()
您的Start方法

中的

答案 1 :(得分:0)

您不应该为Unity组件使用new关键字。

public TextMesh nText = new TextMesh();

应该是

public TextMesh nText = null;

 void Start () {
        score = (Score)FindObjectOfType(typeof(Score));
        Game.game.bubbles.Add(this);
        nText = gameObject.AddComponent("TextMesh") as TextMesh;
        nText.text = "123";
    }
相关问题