- Home /
RPG Mouse targeting error
Hi! Need help. Im making a rpg and i made a C# script. So i can mark which npc i clicked on. But the problem is the diselect thing.
Code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NpcTargeting : MonoBehaviour
{
public List<Transform> targets = new List<Transform>();
public Transform selectedTarget;
public GameObject myTransform;
public RaycastHit hit = new RaycastHit();
public Ray ray;
// Use this for initialization
void Start ()
{
selectedTarget = null;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
selectedTarget = hit.transform;
targets.Add(selectedTarget);
myTransform = hit.transform.gameObject;
}
}
if(selectedTarget != null)
{
selectedTarget.Find("Graphic/NpcCircle").gameObject.SetActive(true);
}
if(selectedTarget == null)
{
if(targets.Count == 0)
{
myTransform.transform.Find("Graphic/NpcCircle").gameObject.SetActive(false);
}
}
if(targets.Count == 2)
{
targets.Clear();
myTransform.transform.Find("Graphic/NpcCircle").gameObject.SetActive(false);
selectedTarget = null;
}
}
}
I'll get an error where it says "UnassignedReferenceException: The variable myTransform of NpcTargeting has not been assigned."
Answer by Jeff-Kesselman · Jun 06, 2014 at 02:49 PM
You can figure this out yourself.
What does your code do when Physics.Raycast returns false. What value does myTransform have? What value does SelectedTarget have?
Walk it through line by line and you will see it.
What Jeff was is trying to convey is that learning to properly debug your code will be a wonderful thing to add to your $$anonymous$$d toolkit.
myTransform is declared but not initialized as a public field, its default value is null. When you try and use your ray cast hit but it's hit was false, myTransform is not set, yet below there is usage of the variable. Jeff is asking you to think about the condition of when myTransform is never set to a reference of an object... leading to your exact exception.
ok, i declared "myTransform" as null, in the "Start" function. now it gives me a "NullReferenceException: Object reference not set to an instance of an object" error? srry if im little retarded, im new to c# program$$anonymous$$g(1 month).
Your answer
Follow this Question
Related Questions
Error CS0029 1 Answer
I'm Getting Weird Bugs Today 1 Answer
FBX Scale Wobble/Shake problem 0 Answers
Assetbundle sample is not working in unity4.6.1(WP8) 0 Answers
Issues concerning the sample projects 0 Answers