c# - 如何检查以避免层次结构中的游戏对象重复?
问题描述
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);
我只想实例化文本一次。如果运行游戏不再创建相同的文本。
我正在实例化文本游戏对象。
解决方案
使用平台相关编译,以便仅在编辑器中运行的代码永远不会编译为构建。这避免了构建中的膨胀代码。
然后,用于EditorApplication.isPlaying
确保仅在编辑模式下运行的代码不会在播放模式下运行。
#if UNITY_EDITOR //Avoid garbage in the builds
//Editor logic
if(!EditorApplication.isPlaying) //If NOT in play mode
GameObject newText = Instantiate(text);
#endif
推荐阅读
- closures - 带有 let 块的 Julia 闭包 - 这是 kosher 吗?
- php - 根据产品类别更改结帐货币
- vb.net - 执行命令后所有对象的属性始终为空
- javascript - 如何 console.log() 在数组中重复?
- reactjs - React 中的异步 props 传递:如何在 React 中传递更新 redux 存储的密钥?[先从高层组件,再从redux store]
- java - 如何自动刷新TextView
- android - get 方法无法检索所有数据
- azure-functions - Cosmos DB:请求失败,因为客户端无法跨 1 个区域建立到 1 个端点的连接
- node.js - Puppeteer 在 phussion 乘客运行时无法启动铬
- python - 使用 KivyMDList 时打印列表名称