Search code examples
unity-game-engineunityscriptunity3d-2dtools

Trying to change Sprite image but no luck... What am I doing wrong?


this is driving me crazy. I'm working with Unity3d ver5 and have a scene that has a MainCamera at (0,0,-10) and a sprite called BackGround at (0,0,0). Both rotation and scale are (0,0,0) & (1,1,1) respectively. I have a very simple script called BackGround.js attached to the sprite it is a simple and straight forward:

function Start () { 
    var spr = GetComponent.<SpriteRenderer>();
    spr.sprite = Resources.Load("bg") as Sprite;
    Debug.Log(spr.sprite.ToString)  
}

bg is a PNG image located in the Assets folder root.

What I want to achieve is to be able to chose a certain image to use as the BackGround sprite using this script, i.e. I start the BackGround sprite with the Sprite : None, then load the image using the script.

This is not working and I end up with a blue empty screen when I run it. More over the Debug.Log is showing the following: NullReferenceException: A null value was found where an object instance was required.

What am I doing wrong here? Thanks.


Solution

  • I've found the solution for that.

    The: spr.sprite = Resources.Load("bg") as Sprite;

    should be changed to: spr.sprite = Resources.Load("bg", typeof(Sprite)) as Sprite;

    Now working like charm!