I’m making a game where you have to swipe a circle around to avoid squares that come into the screen from all four directions. I’m currently working on randomly spawning the squares and I got the spawning part done, now I need to move them across the screen.
Problem:
-I think I’m referring to the instantiated gameobjects (north,east,south,west) wrong when I transform.Translate them because I get the following error in Unity:
NullReferenceException: Object reference not set to an instance of an object
Square.Update () (at Assets/Square.cs:51)
Any help is appreciated ![]()
public float speed = 1f;
public float spawnTempo = 2f;
public GameObject north;
public GameObject east;
public GameObject south;
public GameObject west;
float startSide = 0;
void Start()
{
InvokeRepeating("SquareSpawn",3f,spawnTempo);
}
void SquareSpawn()
{
//1=north 2=east 3=south 4=west
startSide = UnityEngine.Random.Range(1,5);
Debug.Log(startSide);
if (startSide == 1)
{
Instantiate(north, new Vector2(UnityEngine.Random.Range(-2f, 2f), 5.5f), Quaternion.identity);
}
if (startSide == 2)
{
Instantiate(east, new Vector2(3.5f,UnityEngine.Random.Range(-3.5f,3.5f)), Quaternion.identity);
}
if (startSide == 3)
{
Instantiate(south, new Vector2(UnityEngine.Random.Range(-2f, 2f), -5.5f), Quaternion.identity);
}
if (startSide == 4)
{
Instantiate(west, new Vector2(-3.5f, UnityEngine.Random.Range(-3.5f, 3.5f)), Quaternion.identity);
}
}
void Update()
{
if (startSide == 1)
{
GameObject.Find("north").transform.Translate(Vector2.down * speed);
}
if (startSide == 2)
{
GameObject.Find("east").transform.Translate(Vector2.left * speed);
}
if (startSide == 3)
{
GameObject.Find("south").transform.Translate(Vector2.up * speed);
}
if (startSide == 4)
{
GameObject.Find("west").transform.Translate(Vector2.right * speed);
}
}
}