首页 > 解决方案 > 如何将显示文本和单击事件添加到在 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 对象中,我想添加一个标签和一个点击事件

标签: c#unity3d

解决方案


要将组件添加到代码中的对象,您可以执行以下操作:

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 的函数,或者您选择调用它的任何名称,以处理单击事件。你可能还想让你的按钮不可见,并做任何其他看起来必要的事情。


推荐阅读