- Home /
Problem with clicking to target enemies
So I'm looking to make an isometric game where the player clicks on enemies to target them, and the player will then move towards the enemy and begin attacking.
The player object has the following script attached
using UnityEngine;
using System.Collections;
public class playerControllerScript : MonoBehaviour {
public Transform Target;
public Transform myTransform;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(!Target)
{
Debug.Log("No target");
}
else
{
myTransform = transform;
Debug.DrawLine(transform.position, Target.position);
}
}
public void changeTarget(Transform newTarget)
{
Target = newTarget;
}
}
so that the target is a position the player will move to, rather than an object (I thought this would be easier, all enemies will be spawned when the player gets close enough to the spawn point, and all enemies will have the same targetting script). This is it in the stages of sorting out targetting, attacking and moving will get done soon.
and the enemies have the following script attached
using UnityEngine;
using System.Collections;
public class targettingScript : MonoBehaviour {
public Transform myTransform;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
myTransform = transform;
}
void OnMouseDown()
{
playerControllerScript player = GetComponent<playerControllerScript>();
player.changeTarget(myTransform);
Debug.Log("Clicked on");
}
}
So when an enemy is clicked on, the player will have a new transform to move towards and attack. Again, this is still in the stages of sorting out targetting.
But when I click on a target, I get "NullReferenceException: Object reference not set to an instance of an object targettingScript.OnMouseDown ()" and nothing happens beyond that.
How do I fix this? Thanks in advance.
Answer by davedx · Mar 18, 2012 at 07:37 PM
Your enemies are trying to access the playerControllerScript on themselves, which I guess they don't have? You probably just need to change how you're getting that script. The quick and dirty way would be to use GameObject.Find(playerGameObjectName).GetComponent. Better ways would be to use tagging to find your player object, or to set it with a public field on your enemies.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Can't target another player using mouseButtonUp 0 Answers
Problem with targeting system 0 Answers