我设置战斗文本的脚本给出了例外
本文关键字:脚本 设置 文本 | 更新日期: 2023-09-27 18:33:22
我的TextManager脚本是这样的
using UnityEngine;
using System.Collections;
public class TextManager : MonoBehaviour {
private static TextManager instance;
public RectTransform canvasTransform;
public GameObject textPrefab;
public float speed;
public Vector3 direction;
void Start() {
speed = 1f;
direction = (new Vector3(0,1,0));
}
public static TextManager Instance
{
get
{
if (instance == null)
{
instance = GameObject.FindObjectOfType<TextManager>();
}
return instance;
}
}
public void CreateText(Vector3 position)
{
GameObject sct = (GameObject)Instantiate(textPrefab, position, Quaternion.identity);
sct.transform.SetParent(canvasTransform);
sct.GetComponent<RectTransform>().localScale = new Vector3(0.08f, 0.08f, 0.08f);
sct.GetComponent<CombatText>().Initialize(speed, direction);
}
}
战斗文本是这样的
using System.Collections;
public class CombatText : MonoBehaviour {
private float speed;
private Vector3 direction;
private float fadeTime;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float translation = speed * Time.deltaTime;
transform.Translate(direction * translation);
}
public void Initialize(float speed, Vector3 direction) {
this.speed = speed;
this.direction = direction;
}
}
这就是我称之为TextManager.Instance.CreateText(transform.position)的方式;我不知道为什么它会给出 NullReferenceException:对象引用未设置为对象的实例TextManager.CreateText (Vector3 位置) (at Assets/TextManager/TextManager.cs:37)PlayerControl.Update () (at Assets/Player/PlayerControl.cs:35)
有什么提示吗?
TextManager
类的第 37 行是:sct.GetComponent<CombatText>().Initialize(speed, direction);
此行中唯一可以为空的是GetComponent<CombatText>()
所以要解决这个问题。在扇区中附加要textPrefab
的CombatText
组件,或在运行时添加它:sct.AddComponent<CombatText>().Initialize(speed, direction);
.