Clicking a gameobject help

I managed to get andeees script for clicking a game object and altered it to attempt to click a game object - this is the code that is attached to the object that holds the scripts to handle (almost) everything in my scene:

var target1: Transform;

function Update () {
	target1 = GetComponent(battleBeginSetup).player1Object.GetComponent(Transform);
	if (Input.GetMouseButton(0)) {
		var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		var hit: RaycastHit;
		
		if (Physics.Raycast(ray, hit)) {
			if (hit.transform == target1) {
				print("Hit target 1");
			}
		} else {
			print("Hit nothing");
		}
	}
}

The thing is that the inspector shows during runtime that this object is set as target1, however the scene contains a player standing on a plane. If I click the plane it returns absolutely nothing. Yet if I click outside of the plain, even if I’m clicking the object (ie. player) in question - it returns ‘hit nothing’. Anyone able to help me? I’m almost tearing my hair out :frowning:

Is the plane by any chance in the 'ignore raycast' layer? It must have a collider, is it set to 'is trigger'?

Ah I think I've found the problem (your answer managed to somehow managed to get me to figure it) it seems as though it's a mesh collider issue. Somehow even though the mesh of the collider is the same as the actual player's mesh - it just appears as a weird, hopefully I can sort it out though!

I believe they both have colliders but not sure about a physics material. I'll check that when I get home.

One of the objects didn't have the material assigned to the collider, but doing that didn't make a difference on things when I use Transform.rotate in order to rotate the cylinders. I updated below with the code using addTorque.

1 Answer

1

I have found the solution to your problem! In your “Physics.Raycast” if-statement you must say -

var collider = hit.collider;

if(collider.transform==target1)
{
	print("Hit target 1");
}

Or you could also use the built-in mouse functions. Add a script to the target1 game object saying-

//This function is called when the player has clicked the game object.
//You could also use OnMouseDown but, I suggest using OnMouseUp

function OnMouseUp ()
{
    print("Hit target 1");
}

Hi there, thanks for your reply. I found after some digging it was a collider issue. However there may be a chance something might break further down the line so I appreciate having more avenues to go down =)