Question by
anirban13 · Apr 01, 2016 at 06:15 PM ·
object-reference-error
Please Help!!! I am new to Unity I want to create a GameObject through Scripting and add sprite to it......I have done that but there is an error "Object reference not set to an instance of an object" PLS HELP!!! ASAP!!!
I am having error on line : sr.sprite = Sprite.Create (tex, new Rect (0, 0, tex.width, tex.height), new Vector2 (6.2f, 1f))
Error : Object reference not set to an instance of an object
Here is my code -:
void Start () {
UnityEngine.Object[] allSprites = AssetDatabase.LoadAllAssetsAtPath ("Assets/Sprites/full brick.png") ;
ground = new GameObject ();
ball = new GameObject ();
ground.name = "Ground";
ground.AddComponent<BoxCollider2D> ();
ground.GetComponent<BoxCollider2D> ().isTrigger = false;
SpriteRenderer sr = ground.AddComponent<SpriteRenderer> () as SpriteRenderer;
Texture2D tex = allSprites[1] as Texture2D;
sr.sprite = Sprite.Create (tex, new Rect (0, 0, tex.width, tex.height), new Vector2 (6.2f, 1f));
ground.transform.position = new Vector3 (0.02f,-4.43f,1f);
ground.transform.localScale = new Vector3 (6.2f, 1f, 1f);
}
Comment
You didn't paste the error in the question. Which line is the error happening on? Also format your code so it's easier to read, and desperately crying in the subject title doesn't help your cause either."missing object reference" or something similarly short would've suffice.
sr.sprite = Sprite.Create (tex, new Rect (0, 0, tex.width, tex.height), new Vector2 (6.2f, 1f))
is the error line and error is Object reference not set to an instance of an object
Your answer