How is it possible to add a texture using C# only?

Sorry about my plain question but I am a begginer.

Firstly I create an object link:

public GameObject player;

Then I create an object and bind one to the link:

player = new GameObject(“Player”);

Next I add the component:

player.AddComponent();

I can’t understand how to include an texture into the object without inspector using C# only?

Thank you.

You can either do it this way using the inspector or another Sprite reference in code:

public GameObject player;
public Sprite sprite;

private void Start(){
    SpriteRenderer myRenderer = player.AddComponent<SpriteRenderer>();
    myRenderer.sprite = sprite;
}

Or you can put the Sprite in a folder called “Resources”, and use Resources.Load(path) to get it.

That wouldn’t be a good idea, since sprite atlases don’t work with Resources.Load. In general you should avoid Resources.Load anyway since it will probably be removed eventually. You should typically use the inspector, since that way assets aren’t hard-coded, where you can move them, rename them, etc. and the code will still just work with no changes.

–Eric

1 Like

I must be dumb, my apologies, how do we simply access sprites at runtime in code and what is the command for (without using Resources.Load()) actually storing an image reference

Like I read another post here:

http://forum.unity3d.com/threads/changing-sprites-at-runtime-without-resource-load.400552/

I under stand the code where you tell us to declare a sprite array, but whats the actually image data stored or populated, I’m having a hard time finding simple commands to follow. If we are not supposed to load images from the assets in code, how do we reference the file images at all. I tried reading the Texture2D scripting API but I cant understand what
http://docs.unity3d.com/ScriptReference/Texture2D.LoadImage.html

    // Load a .jpg or .png file by adding .bytes extensions to the file
    // and dragging it on the imageAsset variable.
    public TextAsset imageAsset;
    public void Start() {
        // Create a texture. Texture size does not matter, since
        // LoadImage will replace with with incoming image size.
        Texture2D tex = new Texture2D(2, 2);
        tex.LoadImage(imageAsset.bytes);
        GetComponent<Renderer>().material.mainTexture = tex;
    }

really means, I cant get “Texture2D tex = new Texture2D(2, 2);”, Texture2D(2, 2)??

Use public sprite references.

public Sprite mySprite;  // a sprite
public Sprite[] someSprites;  // many sprites

Also, use prefabs. Instead of trying to fight Unity, use its strengths.

–Eric