【发布时间】:2019-08-27 17:50:44
【问题描述】:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
[ExecuteAlways]
public class AddTextToObject : MonoBehaviour
{
public UnityEngine.GameObject[] objectsToNumber;
public UnityEngine.GameObject text;
public float yPadding;
public bool rotateNumbers = false;
public float rotationSpeed = 10f;
public bool textAbove = false;
public bool textInFront = false;
public bool textOnFaces = false;
private List<GameObject> newTexts = new List<GameObject>();
private MeshRenderer[] renderer;
private Vector3 newPos;
private void Start()
{
renderer = new MeshRenderer[objectsToNumber.Length];
for (int i = 0; i < objectsToNumber.Length; i++)
{
GameObject newText = Instantiate(text);
renderer[i] = newText.GetComponent<MeshRenderer>();
if (textAbove == true)
{
newPos = new Vector3
(
objectsToNumber[i].transform.position.x,
((objectsToNumber[i].transform.position.y + renderer[i].bounds.extents.y) + yPadding),
objectsToNumber[i].transform.position.z
);
}
if (textInFront == true)
{
newPos = new Vector3
(
((objectsToNumber[i].transform.position.x + renderer[i].bounds.extents.x) + yPadding),
objectsToNumber[i].transform.position.y,
objectsToNumber[i].transform.position.z
);
}
newText.transform.position = newPos;
newText.transform.parent = objectsToNumber[i].transform;
newText.name = objectsToNumber[i].name + " Text";
newText.tag = "ObjectToAddText";
newTexts.Add(newText);
var textmesh = newText.GetComponent<TextMesh>();
//textmesh.transform.localRotation = Quaternion.Euler(0, -90, 0);
if (textAbove == true)
{
textmesh.text = i.ToString();
}
if (textInFront == true)
{
textmesh.text = objectsToNumber[i].name;
}
}
}
private void Update()
{
if (rotateNumbers == true)
{
for (int i = 0; i < newTexts.Count; i++)
{
newTexts[i].transform.Rotate(Vector3.up, 10 * rotationSpeed * Time.deltaTime);
}
}
}
}
问题是它在编辑器模式下进行实例化,但如果我正在运行游戏,它会再次实例化文本,然后出现双倍文本。
GameObject newText = Instantiate(text);
我只想实例化文本一次。如果运行游戏不再创建相同的文本。
我正在实例化文本游戏对象。
【问题讨论】: