一、接收方有一个文本,用于显示接收的信息
(一)接收方:
1、UI-Text TextMeshPro,名字自取。如:TitleText
2、给TitleText添加Recipients.cs组件。
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;public class Recipients : MonoBehaviour
{public TextMeshProUGUI TitleText;//在Unity中赋值一个文本(用于接收文本信息)public void initData(string titleText)//接收的文本命名为titleText{TitleText.text = titleText;//在TitleText.text文本中显示接收到的文本内容}
}
3、回到Unity,赋值
(二)发送方:
1、给Canvas添加sender.cs组件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Sender : MonoBehaviour
{public Recipients titleText;void Start(){if (titleText == null){titleText = new Recipients();}CreateTitleText();}public void CreateTitleText(){Recipients t = titleText;t.initData("传递方"); }
}
2、回到Unity,赋值
二、在接收方实例化一个文本,文本中显示接收的信息
(一)接收方:
1、UI-Text TextMeshPro,名字自取。如Text (TMP)
2、为Text (TMP)添加Recipients.cs
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;public class Recipients : MonoBehaviour
{public TextMeshProUGUI TitleText;public void initData(string titleText)//初始化节点的数据(类型是String;名字是titleText)//把接收到的文本命名为titleText//初始化节点的数据,接收一个字符串类型的参数titleText作为标题文本{//使用接收到的文本titleText更新TitleText文本组件的内容TitleText.text = titleText;//将TitleText文本组件的内容设置为接收到的titleText(在TitleText.text文本中显示接收到的文本内容)}}
3、回到Unity赋值
4、将Text (TMP)制成预制体,删除Hierarchy面板上的Text (TMP)
(二)发送方:
1、给Canvas添加 Sender.cs组件
2、打开Sender.cs
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;public class Sender : MonoBehaviour
{public Recipients titleText;// Start is called before the first frame updatevoid Start(){CreateTitleText();}public void CreateTitleText(){Recipients t = Instantiate(titleText, this.transform);//创建一个titleText预制体的实例,并将这个实例赋值给变量t//titleText:要实例化的预制体;this.transform:新实例将作为当前对象(脚本所挂载的物体)的子对象//调用Recipients.cs实例上的initData方法,并传递一个字符串参数t.initData("传递方"); //t:titleText预制体实例;//t.initData();:调用预制体本身携带的公开的方法(在Recipients脚本中创建的方法)//括号内要写类型与接收方要求的相同的数据}
}