Hello Guest

Author Topic: Detecting Sprite touches  (Read 3858 times)

mscowler

  • Newbie
  • *
  • Posts: 5
    • View Profile
Detecting Sprite touches
« on: July 20, 2013, 08:07:17 pm »
After looking at posts on this issue, I have inserted the following code in a script attached to all sprites that I want to check for being touched.

var hit:RaycastHit;
var ray:Ray;

if (Input.GetMouseButtonDown (0)) {
   ray = Camera.main.ScreenPointToRay(Input.mousePosition);
   if (collider.Raycast (ray, hit, 100.0)) Debug.Log (myIndex);
}

Code compiles OK, but when "ray = ..." line is executed, I get message "NullReferenceException UnityEngine.Camera.ScreenPointToRay(Vector 3 position)"

I have one camera (MainCamera). I have attached a box collider to the sprites.

Can anyone explain what I'm doing wrong.  I'm new to Unity and Java, so sorry if this seems trivial.

Also, any comments on whether or not the code as a whole will achieve my object (to obtain the index of the sprite that was touched) would be appreciated.

gary-unikronsoftware

  • 2D Toolkit
  • Jr. Member
  • *
  • Posts: 74
    • View Profile
Re: Detecting Sprite touches
« Reply #1 on: July 20, 2013, 09:45:14 pm »
Select your camera in the Hierarchy window.  In the inspector window just underneath the name of the camera there should be a field called 'Tag' with a drop-down box next to it.  Is this set to 'MainCamera'?  If not, select MainCamera from the drop-down box and see if that fixes it.

mscowler

  • Newbie
  • *
  • Posts: 5
    • View Profile
Re: Detecting Sprite touches
« Reply #2 on: July 20, 2013, 10:17:48 pm »
Yes, this fixed it. Thanks.