c# - 如何将显示文本和单击事件添加到在 Unity 运行时创建的动态预制对象
问题描述
如何将显示文本和单击事件添加到在 Unity 运行时创建的动态预制对象。
这是我的 C# 代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InstantiateMarkerPin : MonoBehaviour
{
[Header("Settings")]
public Vector3 TargetPosition = new Vector3(0.09f, 0.5f, 1.1f);
// Instead of using Resources simply reference the
// created Prefab here
public GameObject gameObjectPinPrefab;
[Header("Outputs")]
public GameObject gameObjectPinInstantiate;
private void Start()
{
TargetPosition = new Vector3(0.09f, 0.5f, 1.1f);
gameObjectPinPrefab = (GameObject)Resources.Load("gameObjectPinPrefab");
//The object the script is attached to
GameObject world = this.gameObject;
//Instantiate the prefab
gameObjectPinInstantiate = Instantiate(gameObjectPinPrefab, TargetPosition, Quaternion.identity, world.transform);
Debug.Log("InstantiateMarkerPin class : Marker Location 2 :X, Y, Z : " + gameObjectPinInstantiate.transform.position);
}
}
在 Pin 对象中,我想添加一个标签和一个点击事件
解决方案
要将组件添加到代码中的对象,您可以执行以下操作:
Text t = gameObject.AddComponent<Text>();
t.text = "Whatever";
除非您添加的对象是 Canvas 的子对象,否则标签也不会呈现。您可能希望在代码中获取对画布的引用并使用gameObject.transform.parent = \\canvas object
关于 onclick,我只需从代码中向该对象添加一个按钮:
Button b = gameObject.AddComponent<Button>();
b.onClick.AddListener(OnClick);
从这里您只需要在其他地方定义一个名为 OnClick 的函数,或者您选择调用它的任何名称,以处理单击事件。你可能还想让你的按钮不可见,并做任何其他看起来必要的事情。
推荐阅读
- jupyter-notebook - Jupyter Notebook 问题 - 自动完成和滚动
- ruby-on-rails - 如何在 Arel 中创建和使用未绑定到列的函数?
- javascript - CSS - 当窗口改变大小时,行内容不会改变大小
- android - Crashlytics 自定义键未出现在崩溃中
- unix - 配置:指定在默认路径之后搜索标题的路径
- python-3.x - 如何在 Pandas 中只为一个 NAN 在 NAN 前后填充 0?
- java - Java ObjectMapper.readValue 将泛型类型转换为 LinkedHashMap
- python - 如何使用 tensorflow 实现坐标下降?
- python - 为什么我的精灵在与地板碰撞时向左移动得更快?游戏
- javascript - Fetch hook 和 NuxtLoading 组件