Friday, November 29, 2019

c# - Unity 5 2D drawing sprites programmatically


How can I draw sprites in Unity 5 programmatically ? I am looking for something similar to spriteBatch.Draw() in XNA. The results I get when I search about it are either outdated http://wiki.unity3d.com/index.php?title=SpriteManager (this was written in 2012), or they are done using the unity interface. All I can find is a Sprite class in UnityEngine.dll. Is this what I need ? How would the drawing work ? I really don't get it.



Answer



Unity does not have this kind of "direct mode" rendering, you won't be calling Draw in any update loops for Unity.


In Unity you need to create a game object, then attach scripts to that game object. Those scripts will control how the object behaves, if and how it's displayed on screen, if it's part of the physics system etc.


To create a new sprite to draw on screen you'll need to create a new game object, then attach the SpriteRenderer script to it and set its sprite.


GameObject go = new GameObject();

SpriteRenderer renderer = go.AddComponent();

renderer.sprite = Resources.Load("Sprites/Player", typeof(Sprite)) as Sprite;

This assumes a directory structure of


-Assets
--Resources
---Sprites
----


For example:


enter image description here


Then you'd had a different script for changing the position, rotation etc, depending how you want it to behave.


The easiest way to accomplish all of this without having to write as much code? Create the game object in the Unity editor first. Once the game object is equipped with the sprite you want and the behavior scripts and all that. Drag and drop it into a resources directory. This creates a prefab. Prefabs are just what they sound like, pre-fabrications. They're complete objects that you can then reference and create on the fly.


You'd create those like:


public void CreateObject(string prefabName) {
GameObject newObject =
GameObject.Instantiate(Resources.Load(prefabName)) as GameObject;
}


This will spawn a clone of the prefab you created before. So, if for example, you'd given your prefab the behavior of moving towards the player and attacking, every time you spawn a new prefab of that type, they will start moving towards the player and attacking. The scripts you only had to write once control all of those game objects.


I think the main difference you're seeing here is the heavy use of components. Which you likely haven't seen in other game engines like XNA. Unity really is a powerful engine, but your frustration comes from trying to use it like other engines, when it's not like other engines. Check out my profile for some training, I added a link for a free trial so you don't have to pay.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...