unity Color的缺省参数

  开发过程中可能会经常碰到Vector3和Color等类型无法使用缺省参数的问题,像Vector3这种,缺省参数的值通常是Vector3.zero,所以可以直接用default(Vector3),但是对于Color来说,default(Color)的值为new Color(0,0,0,0),而我们通常需要值的不会是这个。所以,如果需要的话,我们可以以int的形式代替Color传递颜色值。
  unity中的颜色有Color和Color32,这两者可以隐式转换,Color32的取值范围0~255,也就是byte的取值范围。而int占四个字节,正好可以存储颜色的RGBA四个值。

using UnityEngine;

namespace XFramework
{
    /// <summary>
    /// 此类是为了解决传参类型为Color时不能设置默认值的问题
    /// </summary>
    public class ColorInt32
    {
        public const int cyan = 16777215;
        public const int clear = 0;
        public const int grey = 2139062271;
        public const int gray = 2139062271;
        public const int magenta = -16711681;
        public const int red = -16776961;
        public const int yellow = -1374977;
        public const int black = 255;
        public const int white = -1;
        public const int green = 16711935;
        public const int blue = 65535;

        public static Color32 Int2Color(int i)
        {
            byte[] result = new byte[4];
            result[0] = (byte)((i >> 24));
            result[1] = (byte)((i >> 16));
            result[2] = (byte)((i >> 8));
            result[3] = (byte)(i);
            return new Color32(result[0], result[1], result[2], result[3]);
        }

        public static int Color2Int(Color32 color)
        {
            byte[] result = new byte[4];
            result[0] = color.r;
            result[1] = color.g;
            result[2] = color.b;
            result[3] = color.a;
            return (int)(result[0] << 24 | result[1] << 16 | result[2] << 8 | result[3]);
        }
    }
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值