| texture | 获取 Sprite 图形的纹理。 |
| rect | 要用于 Sprite 的纹理矩形部分。 |
| pivot | Sprite 相对于其图形矩形的轴点。 |
| pixelsPerUnit | Sprite 中对应着世界空间中一个单位的像素数。 |
| extrude | Sprite 网格要向外扩展的量。 |
| meshType | 为 Sprite 生成的网格类型。 |
| border | Sprite 的边框大小 (X=左,Y=下,Z=右,W=上)。 |
| generateFallbackPhysicsShape | 是否为 Sprite 生成默认物理形状。 |
| secondaryTextures | 创建的 Sprite 要使用的二级纹理属性。 |
创建新的 Sprite 对象。
Sprite.Create 创建可以在游戏应用程序中使用的新的 Sprite。需要加载一个纹理并将其分配给 Sprite.Create,以便控制新的 Sprite 的外观。在下面的脚本示例中,在按下按钮时会显示一个新的 Sprite。在 Start 中创建了新的 Sprite。
第二个参数 rect 定义了所使用的子纹理。 rect 参数在纹理的像素中定义。Rect(50.0f, 10.0f, 200.0f, 140.0f) 将创建从 50.0f 到 50.0f + 200.0f = 250.0f 的左到右范围。底部到顶部的范围将是 10.0f 到 10.0f + 140.0f = 150.0f。第三个参数 pivot 确定什么成为 Sprite 的中心。这是一个相对于 rect 的 Vector2,其中 Vector2(0.0f, 0.0f) 是左下角,Vector2(1.0f, 1.0f) 是右上角。 pixelsPerUnit 值控制 Sprite 的大小。将此值减少到每世界 100 个像素以下会增大 Sprite 的大小。 extrude 值定义了围绕 Sprite 的像素数。如果 Sprite 包含在图集内,这会很有用。 meshType 选择使用 FullRect 还是 Tight。最后, border 确定 Sprite 的切分,通常用于定义 Sprite 平铺行为。这些值以像素单位表示。
其他资源:SpriteRenderer 类。
// Create a Sprite at startup. // Assign a Texture to the Sprite when the button is pressed.
using UnityEngine;
public class SpriteCreate : MonoBehaviour { public Texture2D tex; private Sprite mySprite; private SpriteRenderer sr;
void Awake() { sr = gameObject.AddComponent<SpriteRenderer>() as SpriteRenderer; sr.color = new Color(0.9f, 0.9f, 0.9f, 1.0f);
transform.position = new Vector3(1.5f, 1.5f, 0.0f); }
void Start() { mySprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100.0f); }
void OnGUI() { if (GUI.Button(new Rect(10, 10, 100, 30), "Add sprite")) { sr.sprite = mySprite; } } }
以下代码示例演示如何使用次要纹理属性在启动时创建一个精灵。
using UnityEngine;
// Create a Sprite at startup with Secondary Textures properties
public class ExampleClass : MonoBehaviour { void Start() { var texture = new Texture2D(64, 64); var secondaryTexture1 = new Texture2D(64, 64); var secondaryTexture2 = new Texture2D(64, 64); var secondaryTexture3 = new Texture2D(64, 64); var secondarySpriteTexture = new[] { new SecondarySpriteTexture() { name = "_SecondaryTexture1", texture = secondaryTexture1 }, new SecondarySpriteTexture() { name = "_SecondaryTexture2", texture = secondaryTexture2 }, new SecondarySpriteTexture() { name = "_SecondaryTexture3", texture = secondaryTexture3 } };
var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 100, 0, SpriteMeshType.FullRect, Vector4.zero, false, secondarySpriteTexture); int spriteSecondaryTextureCount = sprite.GetSecondaryTextureCount(); } }