简体   繁体   English

如何从另一个 class 更改字符串值?

[英]How I can Change String Value from another class?

public class Class1
{
    public string word;
    public string GetString()
    {
       ....
    }

}




public class Class2 : MonoBehaviour
{

    public Class1[] class1;



    void Start()
    {
        class1 = new Class1[3];
        getText();
    }




    void getText()
    {
        for (int i = 0; i < words.Length; i++)
        {
            class1[i].word = "new Text";
            class1[i].GetString();

        }
    }
}

How I can Change (word) from Class2 ?我如何从Class2更改(单词)?

I get this error: NullReferenceException: Object reference not set to an instance of an object我收到此错误: NullReferenceException: Object reference not set to an instance of an object

While you've initialized the class1 array, all its elements are null s, and you'd need to individually initialize each them before attempting to access their members.当您初始化class1数组时,它的所有元素都是null ,您需要在尝试访问它们的成员之前单独初始化它们。

void getText()
{
    for (int i = 0; i < words.Length; i++)
    {
        class1[i] = new Class1(); // Here!
        class1[i].word = "new Text";
        class1[i].GetString();

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM