This question was
closed Dec 08, 2016 at 06:08 PM by
hexagonius for the following reason:
It's a duplicate from the never and aleady commented on one. Closing this then
Question by
SoraMahiro · Dec 08, 2016 at 04:35 PM ·
c#rpgtetris
Unexplainable NullReferenceException?
So, making a tetris game, and trying to instantiate from a resources folder, here is the stack trace:
namespace GameManager
{
public class GameManager:MonoBehaviour
{
Instantiator instance;
void Start()
{
instance.Spawn();
}
public void CheckInput()
{
var posit = transform.position.y;
if (posit != -10)
{
if (Input.GetKeyUp(KeyCode.RightArrow))
{
transform.position += new Vector3(1, 0, 0);
}
else if (Input.GetKeyUp(KeyCode.LeftArrow))
{
transform.position += new Vector3(-1, 0, 0);
}
else if (Input.GetKeyUp(KeyCode.UpArrow))
{
transform.Rotate(0, 0, 90);
}
else if (Input.GetKeyUp(KeyCode.DownArrow))
{
transform.position += new Vector3(0, -1, 0);
}
}
else
{
return;
}
}
void Update()
{
CheckInput();
}
}
}
Then,
public interface Iinstantiatable
{
void SearchAndCall();
}
public class Instantiator:MonoBehaviour
{
Fire.Fire fireElement;
Ice.Ice iceElement;
Lightning.Lightning lightningElement;
Terra.Terra terraElement;
Water.Water waterElement;
Wind.Wind windElement;
public void Spawn()
{
System.Random RandomElement = new System.Random();
int Case = RandomElement.Next(6);
switch(Case)
{
case 1:
fireElement.SearchAndCall(); break;
case 2:
iceElement.SearchAndCall(); break;
case 3:
lightningElement.SearchAndCall(); break;
case 4:
terraElement.SearchAndCall(); break;
case 5:
waterElement.SearchAndCall(); break;
case 6:
windElement.SearchAndCall(); break;
}
}
void Start()
{
}
void Update()
{
}
}
Then, for example:
namespace Fire
{
public class Fire:MonoBehaviour, Iinstantiatable
{
string TetroName;
public void SearchAndCall()
{
GameObject Tetro = (GameObject)Instantiate(Resources.Load(ChooseFireShape(), typeof(GameObject)), new Vector2(0, 12f), Quaternion.identity);
}
public string ChooseFireShape()
{
System.Random RandomFire = new System.Random();
int Case = RandomFire.Next(9);
switch(Case)
{
case 1:
TetroName = "FireTypes/I_Fire"; break;
case 2:
TetroName = "FireTypes/+_Fire"; break;
case 3:
TetroName = "FireTypes/Dot_Fire"; break;
case 4:
TetroName = "FireTypes/l_Fire"; break;
case 5:
TetroName = "FireTypes/LargeL_Fire"; break;
case 6:
TetroName = "FireTypes/Rect_Fire"; break;
case 7:
TetroName = "FireTypes/Sqr_Fire"; break;
case 8:
TetroName = "FireTypes/T_Fire"; break;
case 9:
TetroName = "FireTypes/U_Fire"; break;
}
return TetroName;
}
void Start()
{
}
void Update()
{
}
}
}
The error occurs at GameManager.instance.Spawn().Following the trace back, I still don't see why there is a NullReferenceException. Any ideas why? Or maybe a bug in my code?
Comment