I was trying to make a very simple card game and i want the player to choose a tile to place his card in, and I came up with this script attached to a button that lets the user choose one of the animated tiles and spawns the creature described in the card when the player clics on one of those tiles. I’m a beginner so the script might be quite bad. My english is not good either.
public GameObject Creature;
public GameObject Tile;
Animator anim;
bool IsChoosing = false;
void Start()
{
anim = Tile.GetComponent<Animator>();
}
public void OnClick()
{
anim.SetBool("IsSelecting", true);
IsChoosing = true;
}
void Update()
{
if (Input.GetMouseButtonUp(0) && IsChoosing == true)
{
Vector3 mouse3d = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mouse = new Vector2(mouse3d.x, mouse3d.y);
RaycastHit2D hit = Physics2D.Raycast(mouse, Vector2.zero);
if (hit.transform.gameObject != null)
{
if (hit.transform.gameObject.tag == "Tile" && hit.transform.GetComponent<Select>().isOccupied == false)
{
GameObject MyCreature = Instantiate(Creature, hit.transform.position + new Vector3(0, 0.2f, 0), Quaternion.identity);
MyCreature.transform.SetParent(hit.transform);
anim.SetBool("IsSelecting", false);
IsChoosing = false;
}
}
}
}
It seems to be working fine but the console writes an error every time I use it:
NullReferenceException: Object reference not set to an instance of an object
SpawnCreature.Update () (at Assets/SpawnCreature.cs:30)
Why? Also feel free to give me advice about the script itself. As I said before I’m a beginner.