Unity中结构体定义的成员如何显示在窗口中

在Unity中,有时候我们在处理数据的时候会用到结构体定义一些Unity组件相关的数据成员,并且需要在编辑器中拉取对象赋值。比如:

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

public struct picData
{
    public RawImage Img;
    public Text text;
    public string name;
}


public class StructTest : MonoBehaviour
{
    public picData data;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

上面案例中,首先定义了个picData数据结构,包含我们需要在场景中赋值的Img、text成员,然后我们在主对象中声明了一个公共的结构体变量data。但是在Unity窗口中找不到结构体所定义的成员。

如何实现结构体定义的成员显示在窗口中?

事实上,它有两个必要条件:

1、成员定义为公共成员;

2、在定义结构体变量时要标记结构体为可序列化的。

最终定义如下:

using System;

[Serializable]
public struct picData
{
    public RawImage Img;
    public Text text;
    public string name;
}

在Unity窗口中我们就看到成员显示出来了:

 

可根据需要拉取相关组件直接赋值。

猜你喜欢

转载自blog.csdn.net/mr_five55/article/details/134938217