我在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.
答案 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";
}