Object renders sprite successfully but when trying to replace the sprite Null Reference Exception happens. Can someone please debug and help me understand the problem?
Hi, I'm new to unity and have a question regarding a segment of code I'm having trouble with. When I declare a die object in the main script it properly renders the Blank sprite so I know the object is created and not "null." However, when I try calling the PlaceMultiplier function it throws the NullReferenceException and through debugging I know the die becomes a "null" object. Im confused as to why this is happening, I'm hoping to get a fix and also learn from the explanation, thanks!
using UnityEngine; using System.Collections;
public class Die : MonoBehaviour {
public Sprite Dice1;
public Sprite Blank;
public Sprite Multiplier1;
public Sprite Multiplier2;
public Sprite Multiplier3;
public Sprite Multiplier4;
public Sprite Multiplier5;
public Sprite Multiplier6;
public Sprite Multiplier7;
public Sprite Multiplier8;
private SpriteRenderer spriteRenderer;
// Use this for initialization
void Start () {
Debug.Log ("I DID MAKE IT TO THE START FUNCTION");
spriteRenderer = GetComponent<SpriteRenderer> ();
if (spriteRenderer.sprite == null) {
spriteRenderer.sprite = Blank;
}
}
// Update is called once per frame
void Update () {
if (MainGame.counter <= 5) {
if (MainGame.counter == 0) {
if (MainGame.winSprite > 1) {
Debug.Log ("MADE IT TO THE UPDATE FUNCTION");
if (MainGame.winSprite == 2) {
PlaceMultiplier (2);
}
if (MainGame.winSprite == 3) {
PlaceMultiplier (3);
}
if (MainGame.winSprite == 4) {
PlaceMultiplier (7);
}
if (MainGame.winSprite == 5) {
PlaceMultiplier (8);
}
if (MainGame.winSprite == 6) {
PlaceMultiplier (9);
}
if (MainGame.winSprite == 7) {
PlaceMultiplier (10);
}
if (MainGame.winSprite == 8) {
PlaceMultiplier (15);
}
if (MainGame.winSprite == 9) {
PlaceMultiplier (25);
}
}
}
}
}
public void PlaceMultiplier (int multiple){
if (multiple == 2) {
spriteRenderer.sprite = Multiplier1;
}
if (multiple == 3) {
spriteRenderer.sprite = Multiplier2;
}
if (multiple == 7) {
spriteRenderer.sprite = Multiplier3;
}
if (multiple == 8) {
spriteRenderer.sprite = Multiplier4;
}
if (multiple == 9) {
spriteRenderer.sprite = Multiplier5;
}
if (multiple == 10) {
spriteRenderer.sprite = Multiplier6;
}
if (multiple == 15) {
spriteRenderer.sprite = Multiplier7;
}
if (multiple == 25) {
spriteRenderer.sprite = Multiplier8;
}
}
}
Your answer
Follow this Question
Related Questions
how do i remember a just instantiated prefab as a variable gameobject? 1 Answer
Return key triggering a button OnClick? 1 Answer
Objects are created in the same location. 0 Answers
Suggest best hosting server for multiplayer Game??? 0 Answers
Accessing variable from another gameobject does not work 2 Answers