Unity:如何将self作为另一个方法的参数传递c#

时间:2018-08-19 00:40:02

标签: c# unity3d

假设我有以下代码:

public Text someText;

someText.text = ReturnSomeText();

非常简单。 现在这里是ReturnSomeText()方法代码:

public string ReturnSomeText()
{
    // I want to do some stuff here before returning the text like :
    // I want to set fontstyle of someText to Bold
    // from outside I can just simply set someText.fontstyle = FontStyle.Bold;

   // I have a solution, but I don't like it :
   // I can change ReturnSomeText() structure to ReturnSomeText(Text _text)
   // Then I can say someText.text = ReturnSomeText(someText);
   // but this is not what I want
   // because I am planning to call/use this method many times in many occasions, 
   // I don't want to adjust for every time
   // is there any other smart way.

    return "Hello World";
}

谢谢

1 个答案:

答案 0 :(得分:0)

创建UI文本预制

创建一个空的GameObject并附加以下脚本。当您必须附加自己的字体或想要以统一的内置类型使用的任何字体时,将Text预制件分配给此脚本(MyText.cs)。之后,您可以使用代码动态实例化文本预制件,并设置好位置以描述1000个大量文本,而我只为一个预制件做过

MyText.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MyText : MonoBehaviour {

    class TextProperty
    {
        public Font font { set; get; }
        public string textValue { set; get; }
        public FontStyle fontStyle { set; get; }
        public int fontSize { set; get; }
    }
    public Font font;
    public Text t;
    // Use this for initialization
    void Start()
    {
        var yourT = Instantiate(t, t.transform.position, Quaternion.identity) as Text;
        yourT.transform.SetParent(GameObject.Find("Canvas").transform, false);
        this.SetTextProps(yourT, this.ReturnSomeText());
    }
    void SetTextProps(Text yourText, TextProperty tp)
    {
        yourText.text = tp.textValue;
        yourText.font = tp.font;
        yourText.fontStyle = tp.fontStyle;
        yourText.fontSize = tp.fontSize;
    }
    TextProperty ReturnSomeText()
    {
        TextProperty tp = new TextProperty();
        tp.font = font;
        tp.fontStyle = FontStyle.Bold;
        tp.textValue = "Hello World";
        tp.fontSize = 20;
        return tp;
    }
}

创建类型为ReturnSomeText(...)的许多方法,这些方法将具有一些参数,以便区分更多文本或您想要为其分配的任何属性。对于每个不同的Text,您必须具有预制的和公开的使用ReturnSomeText()类型的新方法声明文本并通过检查器使用字体进行赋值,同时将属性设置为它。 在动态级别的对象上工作时,这些东西效果很好。

相关问题