'Unity C# finding GameObjects using tags
I am just starting out with Unity and C# and i am trying to make an enemy chase after the player. For the enemy to find and chase the player i am using the following code:
public GameObject attackingg;
public Entity attacking;
public int distance;
private bool canAttack;
void Start () {
canAttack = true;
if(attackingg = null){
attackingg = GameObject.FindGameObjectWithTag("Player");
attacking = attackingg.GetComponent<Entity>();
}
}
void Update () {
if(attacking.rigidbody2D.transform.position.y>rigidbody2D.transform.position.y - distance)
{
rigidbody2D.transform.position += Vector3.up * speed * Time.deltaTime;
}
if(attacking.rigidbody2D.transform.position.y<rigidbody2D.transform.position.y - distance)
{
rigidbody2D.transform.position += Vector3.down * speed * Time.deltaTime;
}
if(attacking.rigidbody2D.transform.position.x>rigidbody2D.transform.position.x+ distance)
{
rigidbody2D.transform.position += Vector3.right * speed * Time.deltaTime;
}
if(attacking.rigidbody2D.transform.position.x<rigidbody2D.transform.position.x - distance)
{
rigidbody2D.transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Vector2.Distance (rigidbody2D.transform.position, attacking.transform.position) <= distance && canAttack) {
attackEntity();
StartCoroutine(waitForAttack());
}
}
When running the game, i get the following error:
NullReferenceException: Object reference not set to an instance of an object AttackingMob.Update () (at Assets/Code/Entities/Mobs/AttackingMob.cs:22)
Why is this happening and what can i do to fix my problem? I really appreciate any help, thanks.
Solution 1:[1]
You need to tag the player with the "Player" tag. You have to do this through the editor window in Unity.
The other problem you have is that you are trying to assign null instead of actually checking for null.
if(attackingg = null)
{}
should be:
if(attackingg == null)
{}
Solution 2:[2]
You need to add the "Player tag to the Player GameObject in the Inspector.
And the error:
Object reference not set to an instance of an object
Just check that you have assigned the respective GameObject in the Inspector.
And also, in the line
if (attacking = null) {}
You are supposed to check that the GameObject is NULL by replacing "=" with "=="
Solution 3:[3]
You are assigning null instead of checking null.
Your code
if (attackingg = null)
should be
if (attackingg == null)
In order not to cause this NullPointerException, just assign variable in inspector if the gameobject already spawned in the scene because you already have global variable for that.
public GameObject attackingg = null; // assign gameobject
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | apxcode |
Solution 2 | Dhruv Anand |
Solution 3 | developer0223 |