Hi,
I have a little problem that makes absolutely no sense to me. The following script works perfectly:
using UnityEngine;
using System.Collections;
public class VillagerSelection : MonoBehaviour {
public bool villagerSelected = false;
void FixedUpdate () {
if (Input.GetMouseButtonDown (0) && villagerSelected == false)
{
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero);
if (hit.collider.tag == "Villager")
{
Debug.Log ("Selected");
villagerSelected = true;
}
}
}
}
But, in this following script I’m trying to raycasthit other tags. They cant be found however, and I get
‘C# Object reference not set to an instance of an object’. It can still find the Villager tag, but not ground or trees.
using UnityEngine;
using System.Collections;
public class VillagerController : MonoBehaviour {
public float speed;
public GameObject Something;
private VillagerSelection villagerselection;
void Awake()
{
villagerselection = Something.GetComponent<VillagerSelection> ();
}
void FixedUpdate()
{
if(villagerselection.villagerSelected == true && Input.GetMouseButtonDown(0) )
{
Debug.Log("working");
var mousepos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(mousepos, Vector2.zero);
if(hit.collider.tag == "Ground")
//if( Physics2D.Raycast( ) && hit.collider.gameObject.tag == "Player" )
{
Debug.Log("Ground is nice");
mousepos.z = transform.position.z;
Quaternion rot = Quaternion.LookRotation (transform.position - mousepos, Vector3.forward);
transform.rotation = rot;
transform.eulerAngles = new Vector3 (0, 0, transform.eulerAngles.z);
rigidbody2D.angularVelocity = 0;
transform.position = Vector2.Lerp(transform.position, mousepos, speed * Time.deltaTime);
}
else if(hit.collider.tag == "Tree")
{
Debug.Log("Trees are nice");
}
else if (hit.collider.tag == "Villager")
{
Debug.Log ("Villagers are nice");
//villagerSelected = true;
}
}
}
}
If it wouldnt find the villagers, I would assume that I am doing something completely wrong… but I dont see how it can find the villager tag only.
Any help would be greatly appreciated