分类

链接

2021 年 12 月
 12345
6789101112
13141516171819
20212223242526
2728293031  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > Unity3D > 正文
共享办公室出租
Unity3D: 自制提示框消息 (Toast)
Unity3D 暂无评论 阅读(120)

根据 字符串长度 自适配窗体大小,绑定当前UI父节点:

        // arg0: 提示信息
        // arg1: 提示框体父节点
        public void ShowToastUI(string str, Transform trans)
        {
            GameObject toast = Resources<span class="hljs-preprocessor">.Load</span>(<span class="hljs-string">"XXX"</span>) as GameObject<span class="hljs-comment">; // 加载预制体</span>
            GameObject m_toast = Instantiate(toast, null, true)<span class="hljs-comment">;    // 对象初始化</span>
            m_toast<span class="hljs-preprocessor">.transform</span><span class="hljs-preprocessor">.parent</span> = trans<span class="hljs-comment">;</span>
            m_toast<span class="hljs-preprocessor">.transform</span><span class="hljs-preprocessor">.localScale</span> = Vector3<span class="hljs-preprocessor">.one</span><span class="hljs-comment">;</span>
            m_toast<span class="hljs-preprocessor">.transform</span><span class="hljs-preprocessor">.localPosition</span> = Vector3<span class="hljs-preprocessor">.zero</span><span class="hljs-comment">;</span>
            RectTransform transform = m_toast<span class="hljs-preprocessor">.transform</span><span class="hljs-preprocessor">.GetComponent</span>()<span class="hljs-comment">;</span>
            Text tips = m_toast<span class="hljs-preprocessor">.transform</span><span class="hljs-preprocessor">.FindChild</span>(<span class="hljs-string">"lab_toast"</span>)<span class="hljs-preprocessor">.GetComponent</span>()<span class="hljs-comment">;</span>
            tips<span class="hljs-preprocessor">.text</span> = str<span class="hljs-comment">; </span>
            // 根据字符长度,适配窗体大小
            // arg0: 字符串长度*文本字体大小,再加上边距为提示窗体的宽度
            // arg1: 提示窗体高度 <span class="hljs-number">45</span> (可根据自己需求做适当修改)
            transform<span class="hljs-preprocessor">.sizeDelta</span> = new Vector2(str<span class="hljs-preprocessor">.Length</span> * tips<span class="hljs-preprocessor">.fontSize</span> + <span class="hljs-number">35</span>, <span class="hljs-number">45</span>)<span class="hljs-comment">;</span>

            GameObject<span class="hljs-preprocessor">.Destroy</span>(m_toast, <span class="hljs-number">2</span>)<span class="hljs-comment">;</span>
        }

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:Unity3D: 自制提示框消息 (Toast) | Bruce's Blog

发表评论

留言无头像?