如何防止在c#中静态方法内部设置成员变量的覆盖

时间:2016-06-25 13:36:31

标签: c# unity3d

我遇到的问题是我的类中的变量,它是在类的静态方法中设置的;被该方法的其他调用不断覆盖。

为了更好地理解,此脚本用于动态创建纹理,宽度和高度仅为1个像素。 在使用中这个纹理可以被"拉伸"在一个地区。但是纹理无法保存。这很好。

public class DrawPixelTexture
{
    private static Texture2D t1 = new Texture2D(1, 1, TextureFormat.RGBA32, true);

    static DrawPixelTexture()
    {
        t1.hideFlags = HideFlags.HideAndDontSave;
    }

    public static void Texture(Rect rect, Color colour, float opacity = 1)
    {
        colour.a = opacity;

        // ensure that we only call Apply() once by reading the colour of the pixel at 0,0
        // and seeing id it is the same as 'colour'
        if (t1.GetPixel(0, 0) != colour)
        {
            Debug.Log("still being overriden");

            t1.SetPixel(0, 0, colour);
            t1.Apply();
        }

        Graphics.DrawTexture(rect, t1);
    }
}

这是一个用法示例

public class TestDrawTexture
{
    void OnGUI()
    {
        DrawPixelTexture.Texture(new Rect(0, 0, 100, 20), Color.gray);
        DrawPixelTexture.Texture(new Rect(0, 0, 100, 20), Color.blue);
    }
}

"仍在被覆盖"将被打印出来,因为设置的灰色然后被蓝色覆盖,反之亦然

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

这正是static应该做的事情,只有它的实例。 从函数和变量中删除 DrawPixelTexture,然后创建gray的2个实例。一个用于blue,另一个用于Image

请注意,您不应该使用OnGUI功能。要显示用户界面,请使用RawImageSpriteRenderer组件,然后为其指定纹理。如果这只是一个2D Sprite,那么使用OnGUI不要使用DrawPixelTexture

public class DrawPixelTexture { private Texture2D t1 = new Texture2D(1, 1, TextureFormat.RGBA32, true); public DrawPixelTexture() { t1.hideFlags = HideFlags.HideAndDontSave; } public void txture(Rect rect, Color colour, float opacity = 1) { colour.a = opacity; // ensure that we only call Apply() once by reading the colour of the pixel at 0,0 and seeing id it is the same as 'colour' if (t1.GetPixel(0, 0) != colour) { Debug.Log("still being overriden"); t1.SetPixel(0, 0, colour); t1.Apply(); } Graphics.DrawTexture(rect, t1); } } 脚本:

TestDrawTexture

public class TestDrawTexture : MonoBehaviour { DrawPixelTexture gray; DrawPixelTexture blue; bool firstRun; // Use this for initialization void OnGUI() { if (firstRun) { gray = new DrawPixelTexture(); blue = new DrawPixelTexture(); firstRun = false; } gray.txture(new Rect(0, 0, 100, 20), Color.gray); blue.txture(new Rect(0, 0, 100, 20), Color.blue); } } 脚本:

Self

答案 1 :(得分:0)

我建议创建一个缓存,用于存储已使用的每种颜色的纹理。

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w!@#$%^&*?~()-]{8,}$