2
\$\begingroup\$

Busy following a Quill18 Tutorial for a Tower defence game and It keeps giving me an error(NullReferenceException: Object reference not set to an instance of an object Solution 'TowerDefence') Now I have even downloaded his code and I have mine exactly the same. So either Its the newer version of Unity that is causing the issue or I'm missing something.

I would appreciate it if someone could help me find the missing link here. Thank you

I have attached the code below

public class Turret : MonoBehaviour {

public Transform turretTransform;

// Use this for initialization
void Start()
{
    turretTransform = turretTransform.Find("Turret");
}
    // Update is called once per frame
    void Update()
{//TODO: Optimize this!
        Enemy[] enemies = GameObject.FindObjectsOfType<Enemy>();

        Enemy nearestEnemy = null;
        float dist = Mathf.Infinity;
        foreach (Enemy e in enemies)
        {
            float d = Vector3.Distance(this.transform.position, e.transform.position);
            if (nearestEnemy == null || d < dist)
            {
                nearestEnemy = e;
                dist = d;
            }
        }
        if (nearestEnemy == null)
        {
            Debug.Log("No Enemies");
            return;
        }
        Vector3 dir = nearestEnemy.transform.position - this.transform.position;

        Quaternion lookrot = Quaternion.LookRotation(dir);

        //Debug.Log(lookrot.eulerAngles.y);

        turretTransform.transform.rotation = Quaternion.Euler(0, lookrot.eulerAngles.y, 0);
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ Have you tried running a debugger on this code? It will help to show you the exact object that is set to null. \$\endgroup\$
    – Iggy
    Commented May 13, 2016 at 11:16
  • \$\begingroup\$ Make a minimal example. What is the shortest code that you can think of that still produces this error? \$\endgroup\$
    – Anko
    Commented May 15, 2016 at 23:53

1 Answer 1

1
\$\begingroup\$

Ok, I figured it out! I needed to make sure that when it found "turret" it needed to look for the transform.

void Start()
{
    turretTransform = turretTransform.Find("Turret").transform;
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .