Unity中Prefab实例化敌人时UI生命值文本不加载的问题
代码实例化带World Space Canvas生命值文本的敌人Prefab时文本不显示,但直接拖拽到场景正常
我制作了一个采用World Space渲染模式的Canvas,用于在敌人前方显示其生命值文本。将包含该文本子对象的Enemy制作成Prefab后,通过代码实例化敌人时,文本无法正常显示,但直接将Prefab拖拽到场景中却能正常工作。以下是相关脚本代码及截图:
Enemy控制脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EnemyControl : MonoBehaviour { public Text HealthText; public int Health = 20; // Start is called before the first frame update void Start() { UpdateLifeDisplay(); } // Update is called once per frame void Update() { Death(); UpdateLifeDisplay(); } public void Death() { if(Health < 0) { Destroy(this.gameObject); } } void UpdateLifeDisplay() { if (HealthText != null) { HealthText.text = Health.ToString(); } else { Debug.Log("LifeDisplay null"); } } }
生成器脚本(SpawnHandle)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnHandle : MonoBehaviour { //Upgrades public GameObject[] Upgrades; private int counter = 0; public Transform SpawnPoint; public Transform locA, locB; //Enemy public GameObject enemyPref; public Transform[] eSpawn; private int Ecounter = 0; void Start() { counter++; Ecounter++; } void Update() { if (counter > 0) { int randomIndex = Random.Range(0, Upgrades.Length ); int randomIndex2 = Random.Range(0, Upgrades.Length ); Instantiate(Upgrades[randomIndex], locA.position, SpawnPoint.rotation); Instantiate(Upgrades[randomIndex2], locB.position, SpawnPoint.rotation); counter = 0; StartCoroutine(increase()); } if (Ecounter > 0) { int randomE = Random.Range(0, 2); Instantiate(enemyPref, eSpawn[randomE].position, SpawnPoint.rotation); Ecounter = 0; StartCoroutine(EnemyCounter()); } } void spawn() { } IEnumerator increase() { yield return new WaitForSeconds(10f); counter++; } IEnumerator EnemyCounter() { yield return new WaitForSeconds(3.33f); Ecounter++; } }
文本脚本(FloatingText)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FloatingText : MonoBehaviour { public Transform mainCam; public Transform target; public Transform worldSpaceCanvas; public Vector3 offset; private void Start() { mainCam = Camera.main.transform; transform.SetParent(worldSpaceCanvas); } void Update() { if (target == null) { Destroy(this.gameObject); return; } transform.rotation = Quaternion.LookRotation(transform.position - mainCam.transform.position); // 朝向相机 transform.position = target.position + offset; } }
相关截图
Prefab截图

UI截图

内容的提问来源于stack exchange,提问作者Qatawneh Razvan
相关产品推荐
相关产品推荐

