- Home /
Clicked object is stored in a variable?
I'm currently working on a piece of code that will allow me to move different objects depending on what I click on however I'm having some trouble finalizing it.
The idea is simple, I have a variable called target...
var target: Transform;
...and I use this variable throughout the code. Currently however I have to preset this to an object from my scene (drag and drop it into the slot). What I need to be able to do is basically say
target = object clicked on
I've looked into mouse ray casting but got the error "Cannot convert UnityEngine.GameObject to UnityEngine.Transform".
if (Physics.Raycast (ray, hit, 100))
{
if(hit.collider.gameObject.tag == "Cube")
{
target = hit.transform.gameObject;
}
}
Any help would be greatly appreciated.
Answer by robertbu · Aug 11, 2013 at 06:53 PM
Your 'target' is a Transform, so line 5 should be:
target = hit.transform;
Tried that and get the error "Object reference not set to an instance of an object". The error says its line 25 which is the if (Physics.Raycast (ray, hit, 100)).
Just some more info as well, I'm having this script tied to the camera, I want it to be able to work for any object in the game, rather than placing the same script on hundreds of cubes over and over.
I'd have to see the error in context to see what is going on. $$anonymous$$ost likely you are not handling a null Transform. That is, the target only get's assigned to hit.transform if the Raycast() hits something. If it does not, target is not changed. So unless you are giving it some initial value in the Inspector, it will be null. And trying to access a null reference generates the error.
So you probably need to do something like this around the code that uses target:
if (target != null) {
}
I don't have anything to handle a null transform yet but I don't see how that can be an issue right now. There should never be a null because it only triggers when the mouse is down and I only click the mouse over the object so it should always hit something?