kingBook

导航

unity/C# 结构体属性使用set和get访问器应注意的问题

结构体属性使用set和get访问器时,只能通过"="赋值对属性进行改变,因为你永远只能访问到属性的副本,不会改变属性本身。

using UnityEngine;
using System.Collections;

public class Test:MonoBehaviour{
    
    private Vector2 m_size;
    public Vector2 size{get; private set;}

    private void Start(){
        m_size.Set(1,1);
        Debug.Log("m_size:"+m_size);//output: m_size:(1.0, 1.0)

        size.Set(1,1);
        Debug.Log("sizeA:"+size);//ouput: sizeA:(0.0, 0.0)

        size=new Vector2(0.5f,0.5f);
        Debug.Log("sizeB:"+size);//ouput: sizeB:(0.5, 0.5)

        size.Set(0.6f,0.6f);
        Debug.Log("sizeC:"+size);//ouput: sizeC:(0.5, 0.5)
    }
}

posted on 2020-05-08 14:54  kingBook  阅读(876)  评论(0)    收藏  举报