Detect if Game Object has been clicked on in 3Dspace

hey so ive been looking around and struggled to find anything on that fitted with what i needed. Anyway so im looking to click on a gameobject while in game then afterwards i want to use that as my target for my missile script however when i come to run it, its saying its not reference to the instance of the object… have i missed something out or does the way im finding the gameobject from the mouse click not like to be used later on in the script? thanks tones in advance here’s my code so far:

using UnityEngine;
using System.Collections;

public class turretplayer : MonoBehaviour {

Transform enemy;
public GameObject Missile;
public float enemyDist;
public GameObject spawn;
bool Space = Input.GetKey(KeyCode.Space);
bool fire;
Rigidbody rb;

void OnMouseDown()
{
enemy = gameObject.transform;

}

void Start() { rb = GetComponent(); }

void Update () {

//calc enemy dist
enemyDist = Vector3.Distance(transform.position, enemy.position);
//if enemy is close by
if (enemyDist <= 100)
{
Quaternion neededRotation = Quaternion.LookRotation(transform.position - enemy.position);
transform.rotation = Quaternion.Slerp(transform.rotation, neededRotation, Time.deltaTime * 0.5f);
if(Space == true)
{
Instantiate(Missile, spawn.transform.position, spawn.transform.rotation);
rb.AddForce(transform.forward * 10F);
}
}
}
}

What you wrote:

Transform enemy;

void OnMouseDown()
{
    enemy = gameObject.transform;
}

What’s enemy? Since you didn’t declare the GameObject via script, you need to drag the “enemy” in the editor, which you didn’t do. That’s why you have the error. Basically, you need a reference to the “enemy” GameObject.

I’m done talking about the error but your approach is problematic. What were you trying to accomplish by setting the position of the enemy to this current GameObject’s position when this GameObject is clicked? If you put that to practice, what would happen is that the player clicks on the GameObject this script is attached to and then the enemies will teleport to this GameObject. Are you sure this is what you want?