0
votes

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.

2
First of all the PNG needs to be in a folder named "Resources" (A subfolder of Assets), otherwise it isn't available with a Resources.Load call. And did you set it to be a Sprite in the inspector?Bart
First of all I would like to thank you guys for your help. I've created the folder and moved bg to that folder and made sure it is set to sprite and still not loading, will try to add a screen shot for the current situation.@Mihai-Andrei Dinculescu @hades2510TDEgypt
Here is the screen shot: dl.dropboxusercontent.com/u/47430002/…TDEgypt

2 Answers

0
votes

For your resource to be loaded via Resources.Load your asset needs to be placed under a folder named Resources, it isn't mandatory for the folder's parent to be Assets but it needs to be named Resources.

You may have multiple Resources folder under your project and Unity will look in all of them to try to locate your resource. This is important because you may have the same path for a resource when calling Resources.Load but multiple resources that match it, so you need to be careful.

That being said you should create a folder named Resources and add your png there.

0
votes

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!