L
L
Lovelybit2020-04-25 14:08:50
Unity
Lovelybit, 2020-04-25 14:08:50

Why is a Null reference exception thrown?

Hello! At an emphasis I can not understand why the Null reference exception error takes off. When trying to use the method from the PlayerController "GetDestinationOfAttack()" in the Attacker script. The analysis showed that the destination variable in the Attacker script still remains null. Please help me figure it out.

The code below is from two scripts (Attacker) and (PlayerController):

using UnityEngine;

public class Attacker : MonoBehaviour
{
[SerializeField] float speed = 1f;
PlayerController playerController;
transform destination = null;

// Start is called before the first frame update
void Start()
{
playerController = GetComponent();
destination = playerController.GetDestinationOfAttack();
}
}

public class PlayerController : MonoBehaviour
{
[SerializeField] GameObject unitProducedPrefab = null;

GameObject selectedBase = null;
GameObject previousSelectedBase = null;
bool baseIsSelected = false;
public Transform destinationOfAttack = null;
GameObject castle;
GameObject selectedTarget;

// Start is called before the first frame update

// Update is called once per frame
void Update()
{

}


public void SelectBase(GameObject castle)
{
if (selectedBase != null)
{
previousSelectedBase = selectedBase;
previousSelectedBase.GetComponent().color = Color.white;
previousSelectedBase.GetComponent().SetBoolOfSelectedBase(false);
}
selectedBase = castle;
castle.GetComponent().color = Color.red;
castle.GetComponent().SetBoolOfSelectedBase(true);
baseIsSelected = true;
}

public void Attack(GameObject target)
{
if (baseIsSelected == false) return;
destinationOfAttack = target.GetComponent() as Transform;
Instantiate(unitProducedPrefab, selectedBase.transform.position, transform.rotation);
}

public Transform GetDestinationOfAttack()
{
return destinationOfAttack;
}
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question