I am currently making a Terraria like game. What I want is when I hold the mouse button down on a grass block, I want it to load a breaking animation and when the animation is complete, the block will be destroyed and added to the players’ inventory. Because the terrain is randomly generated, I do not have a gameobject in the hierarchy to represent each block, this would be stupid to have. I simply have a single GrassBlock prefab in the Assets folder and use a for loop to generate the terrain. Now here comes the problem, I do not know how to access the GrassBlock prefab in the code and therefore when I run the game and hold the mouse button on a GrassBlock(Clone) there is not breaking animation. Only if I drag the prefab into the hierarchy and run the game, and then hold the mouse button will there be a breaking animation. Instead of accessing the prefab, I thought to access the GrassBlock(Clone) when the game is run:
Animator blockAnim;
GameObject x;
// Use this for initialization
void Start () {
currentHealth = maxHealth;
rb2D = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
FirePos = transform.Find("FirePosition");
//this is how I would access the GrassBlock(Clone) GameObject
x = GameObject.Find("GrassBlock(Clone)");
blockAnim = x.GetComponent<Animator>();
}
This however gives me this error - NullReferenceException: Object reference not set to an instance of an object. Error is on the follwing lines:
void Start () {
currentHealth = maxHealth;
rb2D = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
FirePos = transform.Find("FirePosition");
//this is how I would access the GrassBlock(Clone) GameObject
x = GameObject.Find("GrassBlock(Clone)");
blockAnim = x.GetComponent<Animator>(); // I get the error here
}
This method is used to check weather the mouse button has been pressed on an a block
public void __BreakBlock__(string blockTagName, GameObject blockToAdd)
{
if (AddToInventory)
{
Inventory.Add(blockToAdd);
}
Vector2 mouse_position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouse_position = new Vector2(Mathf.Round(mouse_position.x), Mathf.Round(mouse_position.y));
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.forward);
if (Input.GetMouseButton(0))
{
if (hit)
{
if (hit.collider.tag == blockTagName && hit.collider.tag != "player")
{
blockAnim.SetInteger("State", 1); //I get the error here
}
}
}
else
{
blockAnim.SetInteger("State", 0); //I get the error here
AddToInventory = false;
}
This is not my entire script as it is more than 300 lines. These are just the lines that are responsible for my issue. If you want to see the entire script, I will provide it.